Python 如何有条件地更新 Pandas 中的 DataFrame 列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18196203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to conditionally update DataFrame column in Pandas
提问by TravisVOX
With this DataFrame, how can I conditionally set rating
to 0 when line_race
is equal to zero?
使用此 DataFrame,如何rating
在line_race
等于0 时有条件地设置为 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
In other words, what is the proper way on a DataFrame to say if ColumnA = x then ColumnB = y else ColumnB = ColumnB
换句话说,如果 ColumnA = x then ColumnB = y else ColumnB = ColumnB,那么在 DataFrame 上的正确方法是什么
采纳答案by Viktor Kerkez
df.loc[df['line_race'] == 0, 'rating'] = 0
回答by SpeedCoder5
Use numpy.whereto say if ColumnA = x then ColumnB = y else ColumnB = ColumnB:
使用numpy.where说if ColumnA = x then ColumnB = y else ColumnB = ColumnB:
df['rating'] = np.where(df['line_race']==0, 0, df['rating'])