我可以不直接调用pandas数据帧上的函数吗



我是熊猫学习的新手,刚刚学习了python,所以我的问题可能看起来很傻。我创建了一个函数来更改数据集中的null值。我试着在数据帧的几列上调用这个函数。

def impute_age(cols):
age = cols[0]
pclass = cols[1]

if pd.isnull(Age):

if pclass == 1:
return 37

elif pclass ==2:
return 29

else:
return 23
else:
return Age

然后我这样称呼它:

train['Age'] = impute_age(train[['Age','Pclass']])

它给出密钥错误:0

我在某个地方查了一下,他用的是:

train['Age'] = train[['Age','Pclass']].apply(impute_age,axis=1)

但在python中,我们调用了类似于上面的函数。有人能告诉我我在这里做错了什么吗。

我会像一样使用它

import pandas as pd
import numpy as np
def impute_age(age, pclass):
if pd.isnull(age):
if pclass == 1:
return 37
elif pclass ==2:
return 29
else:
return 23
else:
return age
df = pd.DataFrame({'Age': [np.nan, np.nan, np.nan, 100], 'Pclass':[1,2,3,4]})
df['Age'] = df.apply(lambda row: impute_age(row['Age'], row['Pclass']), axis=1).astype(int)

输出:

>>> df
Age  Pclass
0   37       1
1   29       2
2   23       3
3  100       4

最新更新