【问题标题】:function utilization - calling using apply vs direct call函数利用 - 使用 apply 调用 vs 直接调用
【发布时间】:2018-02-28 09:13:28
【问题描述】:

我的代码如下。如果我通过第一种方法调用该函数,它可以工作。但是,如果我使用第二种方法调用该函数,则会出现错误。我认为方法二应该起作用,因为该函数期望列作为其输入。为什么我们必须说在方法1中描述的列上运行函数?

trainpandas 数据框。

import pandas as pd

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 24
    else:
        return Age

#pd.isnull(train[['Age']])

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

#method 2
impute_age(train[['Age','Pclass']])

【问题讨论】:

  • 什么是pd,最重要的是:什么是train
  • pd=pandas 和 train 是一个数据框..抱歉造成混淆

标签: python function pandas dataframe apply


【解决方案1】:

我认为首先你需要一个格式良好的代码:

import pandas as pd
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 24

    else:
        return Age


#pd.isnull(train[['Age']])

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

#method 2
impute_age(train[['Age','Pclass']])

一句话,def后面需要缩进。

【讨论】:

    猜你喜欢
    • 2015-11-03
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多