本文介绍了如何在Python中基于两个条件更改列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据集,其中包含游戏时间和事件时间.
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
我要替换GAME<的EVENT栏中的NaN;按GAME列中的值0.24.
I want to replace the NaN in the EVENT column where GAME < 0.24 by the value in the GAME column.
df['EVENT'][(df['GAME'] < '0:24') & (df['EVENT'] == 'NaN')] = df['GAME']
我已经尝试过了,但是没用.抱歉,如果很明显.我是Python的新手.
I have tried this but it dosen't work. Sorry if it is obvious. I am new to Python.
推荐答案
您可以使用 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
使用 mask
的另一种解决方案:
Another solution with 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
或 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
这篇关于如何在Python中基于两个条件更改列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!