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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:20:52  来源:igfitidea点击:

How to change the values of a column based on two conditions in Python

pythonpandasdataframe

提问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 isnullfor 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:

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