Pandas 根据条件操作行

Pandas 根据条件操作行,pandas,Pandas,我想根据条件操纵行。例如,如果type中的字段是numpy-NaN,我想用字符串“BBBB”覆盖method中的每个字段: newcolumn = [] for index, row in results_DF.iterrows(): newcolumn.append('BBBB' if row['type'] is np.nan else row['method']) results_DF['method'] = pd.Series(newcolumn) 这个实现看起来相当丑陋。如何

我想根据条件操纵行。例如,如果
type
中的字段是numpy-NaN,我想用字符串“BBBB”覆盖
method
中的每个字段:

newcolumn = []
for index, row in results_DF.iterrows():
    newcolumn.append('BBBB' if row['type'] is np.nan else row['method'])
results_DF['method'] = pd.Series(newcolumn)
这个实现看起来相当丑陋。如何写得更好-更具功能性?

使用以下创建的布尔amsk:

另一个解决方案包括:

或@Jon Clements提供的解决方案,谢谢:

results_DF['method'] = results_DF.where(results_DF['type'].notnull(), 'BBBB')
样本

results_DF = pd.DataFrame({'method': ['a','s','d'],
                           'type':[np.nan, np.nan, 4]})

print (results_DF)
  method  type
0      a   NaN
1      s   NaN
2      d   4.0

results_DF.loc[results_DF['type'].isna(), 'method'] = 'BBBB'
print (results_DF)
  method  type
0   BBBB   NaN
1   BBBB   NaN
2      d   4.0
试试这个

mask=results_DF['type'].isnull()
results_DF.loc[mask]='BBBB'

mask=results\u DF['type'].isnull()results\u DF.loc[mask]='bbbbbb'或:
results\u DF['method']。其中(results\u DF['type'].notnull(),'bbbbbbbb',inplace=True)
?但它不是空的,是吗?是的,它是空的。欲了解更多详情,请访问
results_DF = pd.DataFrame({'method': ['a','s','d'],
                           'type':[np.nan, np.nan, 4]})

print (results_DF)
  method  type
0      a   NaN
1      s   NaN
2      d   4.0

results_DF.loc[results_DF['type'].isna(), 'method'] = 'BBBB'
print (results_DF)
  method  type
0   BBBB   NaN
1   BBBB   NaN
2      d   4.0
mask=results_DF['type'].isnull()
results_DF.loc[mask]='BBBB'