gpt4 book ai didi

python - 正确使用apply函数去除NAN

转载 作者:行者123 更新时间:2023-12-01 06:50:25 25 4
gpt4 key购买 nike

我在数据框中有一列年龄,其中有 NAN,我试图将其更改为基于某些条件组的意思,但不确定它为什么会中断。如果您看到输出 Post apply 函数,我基本上已经重新创建了一个脚本,可以使用下面的代码进行重现。我仍然看到那里有空值

import pandas as pd
import numpy as np



def find_mean_age(Sex,Typ):
return temp.loc[(temp['Sex']==Sex)&(temp['Typ']==Typ),'Age']

if __name__ =='__main__':
df = pd.DataFrame({'Id':[1,2,3,4,5,6],
'Sex':['male','male','female','male','female','female'],
'Age':[21,float('Nan'),float('Nan'),23,56,32],
'Typ':['A','A','V','V','V','V']})
print(df)

temp = df.loc[(df['Age'].notnull())&(df['Age'] < 65 ),
['Age','Sex','Typ']].groupby(['Sex','Typ'],as_index=False).mean()

df.loc[df['Age'].isnull(), ['Age']] = df.apply(lambda row: find_mean_age(row['Sex'], row['Typ'][0]),
axis=1)

print(df)

输出

   Id     Sex   Age Typ
0 1 male 21.0 A
1 2 male NaN A
2 3 female NaN V
3 4 male 23.0 V
4 5 female 56.0 V
5 6 female 32.0 V

最佳答案

您的函数返回 Series 对象,而不是值。修复您的代码很容易:

def find_mean_age(Sex, Typ):
return temp.loc[(temp['Sex'] == Sex) & (temp['Typ'] == Typ)]['Age'].tolist()[0]

这会产生:

   Id     Sex   Age Typ
0 1 male 21.0 A
1 2 male 21.0 A
2 3 female 44.0 V
3 4 male 23.0 V
4 5 female 56.0 V
5 6 female 32.0 V

应该提到的是,@chris-a 为您的问题提供了最优雅的解决方案。

关于python - 正确使用apply函数去除NAN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59035697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com