【问题标题】:Can i not call directly a function on pandas dataframe?我不能直接调用熊猫数据框上的函数吗?
【发布时间】:2021-08-10 21:12:03
【问题描述】:

我是学习 pandas 的新手,刚刚学习了 python,所以我的问题可能看起来很傻。我创建了一个函数来更改数据集中的空值。我试图在我的数据框的几列上调用该函数。

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 中,我们调用了上述函数。谁能告诉我我在这里做错了什么。

【问题讨论】:

  • 您的函数的设计方式不是让您可以将 DateFrame 作为输入。对于这种情况,我建议使用numpy.select
  • 如果你想使用布尔索引,你应该使用df.iloc[: , colIndex]。当您只使用0 时,pandas 认为它​​是列标签而不是索引。所以这就是你错误的原因。但是有更好的方法来实现您在替换 NaN 值时尝试做的事情。 numpy.where()numpy.select()df.where() 就是这样的方式。

标签: python pandas dataframe numpy data-science


【解决方案1】:

我会像这样使用它

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多