3 回答

TA貢獻1864條經驗 獲得超2個贊
另一種方法是使用 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
輸出

TA貢獻1846條經驗 獲得超7個贊
有幾種方法可以做到這一點,首先你的初始代碼非常接近,你只需要結束分配:
df.loc[df['Flag'] == 1, 'Flag'] = df['val_1']
print(df)
Date val_1 val_2 Flag
0 2018-08-27 221.0 121.0 0.0
1 2018-08-28 222.0 122.0 222.0
2 2018-08-29 223.0 123.0 0.0
3 2018-08-30 224.0 124.0 2.0
4 2018-08-31 225.0 125.0 0.0
你在這里做的是過濾你的數據框并替換條件匹配的值。在這種情況下,Flag 等于 1。
既然你正在做多重評估,讓我們使用np.select
import numpy as np
conditions = [df['Flag'].eq(1),
df['Flag'].eq(2)]
choices = [df['val_1'],df['val_2']]
df['Flag'] = np.select(conditions,choices,default=df['Flag'])
這樣做的目的是評估您擁有的所有條件。將默認值保留為原始列。您可以在其中添加更多條件,并將 OR 語句用 | 括在括號中。(管道)分離器。IE[(df['Flag'] == 1 | df['Flag'] == 2)]
Date val_1 val_2 Flag
0 2018-08-27 221.0 121.0 0.0
1 2018-08-28 222.0 122.0 222.0
2 2018-08-29 223.0 123.0 0.0
3 2018-08-30 224.0 124.0 124.0
4 2018-08-31 225.0 125.0 0.0

TA貢獻1874條經驗 獲得超12個贊
國際大學聯盟:
new_vals = df.lookup(df.index, df.columns[df.Flag-1])
df['Flag'] = df.Flag.mask(df.Flag>0, new_val)
注意:正如@Erfan 所評論的,這也可以:
df['Flag'] = df.lookup(df.index, df.columns[df.Flag-1])
輸出:
val_1 val_2 Flag
Date
2018-08-27 221.0 121.0 0
2018-08-28 222.0 122.0 222
2018-08-29 223.0 123.0 0
2018-08-30 224.0 124.0 124
2018-08-31 225.0 125.0 0
- 3 回答
- 0 關注
- 134 瀏覽
添加回答
舉報