正确使用Apply功能删除NAN

时间:2019-11-25 16:00:41

标签: python pandas dataframe

我在具有NAN的数据框中有一个Age列,我试图将其更改为根据条件按特定组而不是为什么会中断。如果您看到输出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

1 个答案:

答案 0 :(得分:1)

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

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为您的问题提供了最优雅的解决方案。