【问题标题】:Pandas: Running a function to apply on a datasetPandas:运行函数以应用于数据集
【发布时间】:2019-01-18 10:04:12
【问题描述】:

我一直在试图弄清楚如何将两个变量(行)传递给一个函数并获得一个输出,但是我在语法上遇到了很多麻烦。

我一整天都在用头撞墙;这是我已经看过的内容:

(我认为我使用 apply 错误) Pandas: How to apply a function to different columns

Difference between map, applymap and apply methods in Pandas

我重读了申请,但没有帮助。我正在使用泰坦尼克号数据集 (https://github.com/alexisperrier/packt-aml/blob/master/ch4/titanic.csv) 并尝试用设置的数字替换空的年龄。我尝试了两种方法:

Titanic.loc[(Titanic['pclass'] == 1) & (Titanic['age'].isnull()), 'age'] = 35
Titanic.loc[(Titanic['pclass'] == 2) & (Titanic['age'].isnull()), 'age'] = 25
Titanic.loc[(Titanic['pclass'] == 3) & (Titanic['age'].isnull()), 'age'] = 20

(这段代码工作得很好,用预定值替换空的“年龄”)。我的第一次尝试是创建一个函数并应用它。功能:

def ClassAge(age,pclass):
    if age.isnull:
        if pclass == 1:
            n = 35
        if pclass == 2:
            n = 25
        if pclass == 3:
            n = 20
    return(n)

我尝试使用它来应用它:

Titanic.age.apply(ClassAge,Titanic['pclass'], axis=1)

输出:

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

根据我在其他答案中读到的内容,我尝试了这个,因为 apply 假定行是输入。

Titanic[['age','pclass']].apply(ClassAge)

这给了我这个:

TypeError: ("ClassAge() 缺少 1 个必需的位置参数:'pclass'",'发生在索引年龄')

如上所述,我确实使用 .loc 解决了该问题,但出于教育目的,我想了解我在编写函数或调用它(或两者兼而有之)时正在做什么。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    在对行应用 lambda 而不是传递整个系列的 pclass 时,只需传递行值

    df.apply(lambda x: ClassAge(x['age'],x['pclass']), axis=1)
    

    【讨论】:

    • 谢谢,在对我的核心代码稍作改动后,这行得通。 (因为我必须逐行运行 .isnull 将不再起作用;但我稍微更改了代码以使其按预期运行。
    猜你喜欢
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    相关资源
    最近更新 更多