![](/img/trans.png)
[英]How to conditionally update DataFrame column in Pandas based on list
[英]How to conditionally update DataFrame column in Pandas
使用此 DataFrame,當line_race
等於 0 時,如何有條件地將rating
設置為 0?
line_track line_race rating foreign
25 MTH 10 84 False
26 MTH 6 88 False
27 TAM 5 87 False
28 GP 2 86 False
29 GP 7 59 False
30 LCH 0 103 True
31 LEO 0 125 True
32 YOR 0 126 True
33 ASC 0 124 True
換句話說,如果 ColumnA = x then ColumnB = y else ColumnB = ColumnB,那么在 DataFrame 上的正確方法是什么
df.loc[df['line_race'] == 0, 'rating'] = 0
使用numpy.where說if ColumnA = x then ColumnB = y else ColumnB = ColumnB :
df['rating'] = np.where(df['line_race']==0, 0, df['rating'])
我一直使用 Selected answer 中給出的方法,今天我面臨需要更新 A 列的需要,有條件地使用派生值。 接受的答案顯示“如何將列 line_race 更新為 0。下面是一個示例,您必須派生出要更新的值:
df.loc[df['line_race'].isna(), 'rating'] = ( (df['line_race'] - df['line_race2'])/df['line_race2'] )
使用它,您可以僅在匹配條件的行上更新動態值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.