pandas 如何根据Python中的两个条件更改列的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43232753/
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 change the values of a column based on two conditions in Python
提问by Nico Coallier
I have a dataset where I have the time in a game and the time of an event.
我有一个数据集,其中包含游戏时间和事件时间。
EVENT GAME
0:34 0:43
NaN 0:23
2:34 3:43
NaN 4:50
I want to replace the NaN in the EVENT column where GAME < 0.24 by the value in the GAME column.
我想用 GAME 列中的值替换 EVENT 列中 GAME < 0.24 的 NaN。
df['EVENT'][(df['GAME'] < '0:24') & (df['EVENT'] == 'NaN')] = df['GAME']
I have tried this but it dosen't work. Sorry if it is obvious. I am new to Python.
我试过这个,但它不起作用。对不起,如果很明显。我是 Python 的新手。
回答by jezrael
You can use isnull
for check NaN
:
您可以isnull
用于检查NaN
:
df.loc[(df['GAME'] < '0:24') & (df['EVENT'].isnull()), 'EVENT'] = df['GAME']
print (df)
EVENT GAME
0 0:34 0:43
1 0:23 0:23
2 2:34 3:43
3 NaN 4:50
Another solution with mask
:
另一个解决方案mask
:
mask = (df['GAME'] < '0:24') & (df['EVENT'].isnull())
df['EVENT'] = df['EVENT'].mask(mask, df['GAME'])
print (df)
EVENT GAME
0 0:34 0:43
1 0:23 0:23
2 2:34 3:43
3 NaN 4:50
Or numpy.where
:
df['EVENT'] = np.where(mask, df['GAME'], df['EVENT'])
print (df)
EVENT GAME
0 0:34 0:43
1 0:23 0:23
2 2:34 3:43
3 NaN 4:50