Bob*_*Bob 5 python dataframe pandas
我有一个 pandas 数据框,如下所示:
val_1 val_2 Flag
Date
2018-08-27 221.0 121.0 0
2018-08-28 222.0 122.0 1
2018-08-29 223.0 123.0 0
2018-08-30 224.0 124.0 2
2018-08-31 225.0 125.0 0
Run Code Online (Sandbox Code Playgroud)
我想根据标志条件将标志列值更改为与其他列相同的值。即,如果 Flag 为 1,则将 1 替换为同一行中的 val_1;如果 Flag 为 2,则将其替换为 val_2。我正在寻找的输出如下所示:
val_1 val_2 Flag
Date
2018-08-27 221.0 121.0 0
2018-08-28 222.0 122.0 222.0
2018-08-29 223.0 123.0 0
2018-08-30 224.0 124.0 124.0
2018-08-31 225.0 125.0 0
Run Code Online (Sandbox Code Playgroud)
我知道我可以.loc这样使用df.loc[df['Flag'] == 1, ['Flag']] =。我不知道代码右侧是什么。
另一种方法是使用 np.wherenumpy.where(condtion,yes,no)
在这种情况下,我使用嵌套,np.where以便
np.where(If Flag=2,take val_2,(take x)) where takex is another np.where
df['Flag']=np.where(df['Flag']==1,df['val_1'],(np.where(df['Flag']==2,df['val_2'],df['Flag'])))
df
Run Code Online (Sandbox Code Playgroud)
输出