如何使用 python 迭代选定列的 DataFrame?

How to iterate over a DataFrame for a selected coulmn using python?

假设我有这样的示例代码

_d=pd.DataFrame([[1,2,3],[4,np.nan,6],[np.nan,np.nan,8]],columns=['x','y','z'])

现在,我有一个函数可以检查值并根据场景分配所需的值

def handling_nan(_d):
    if _d['x']==1.0:
        return 100
    else:
        return _d

当我在下面的代码中使用它时,

_result=_d.apply(lambda x:handling_nan(x))
_result

我遇到错误

KeyError: ('x', 'occurred at index x')

更新一个:

嗯,简而言之,我正在使用来自 kaggle.com 的数据集,即。 泰坦尼克号:从灾难中学习机器,在那个数据集中,我想介绍一个新的专栏,条件类似于这样。

if male and the age is NaN then insert the mean() age of men instead of NaN and if female and the age is NaN, then insert the mean() of the total female age instead of NaN

KeyError 在函数中遇到,因为数据帧上的 apply() 方法假定 axis=0。这意味着该函数将应用于每一列而不是每一行。要消除此错误,需要将 apply() 调用替换为:

_result=_d.apply(lambda x:handling_nan(x), axis=1)

查看编辑,问题是用数据集中的分组均值替换 NaNs

这可以使用 fillna()transform() 方法完成,如下所示:


l = [["M", 30], ["M", 45], ["M", None], ["F", 76], ["F", 23], ["F", None]]
df = pd.DataFrame(l, columns=["sex", "age"])
df['age'] = df['age'].fillna(df.groupby("sex")['age'].transform('mean'))

This 答案有其他替代解决方案。

希望对您有所帮助。