首页 > 解决方案 > Pandas/Python 循环遍历数据框的行并根据包含 NA'a 的另一列值更改一列

问题描述

我有一个大数据框,我需要循环并根据另一列的相同行值更改一个行值。我已经阅读了这篇文章Pandas/Python: Set value of one column based on value in another column和这篇博文https://towardsdatascience.com/a-really-simple-way-to-edit-row-by-row- in-a-pandas-dataframe-75d339cbd313但这种方法对我不起作用。我认为出错的是我从 (label2) 索引的列在某些行中包含空值。

for index in df.index:
 if df.loc[index,'label2']=='Some label to match':df.loc[index,'label1'] = 'label to change'

有没有办法在熊猫中解决这个问题,例如,在循环中使用 df.notnull() ?我尝试了以下方法,但它不起作用:

df['label2'].notnull(df.loc[index,'label2']=='Some label to match':df.loc[index,'label1'] = 'label to change')

提前致谢!

标签: pythonpandasnull

解决方案


推荐阅读