【问题标题】:Apply custom function to pandas DataFrame returns 'DataFrame' object is not callable将自定义函数应用于 pandas DataFrame 返回“DataFrame”对象不可调用
【发布时间】:2021-06-06 16:09:34
【问题描述】:

嘿嘿,

我在这里的第一篇文章。我试图在这里找到类似的问题,但没有成功。就这样吧。 我有几个单独的熊猫数据框,其中至少一列包含字典,即

fiscalYear | prodID | position
2020       | 123    | {'description': 'Customer Operations', 'code': '51254185'}
2020       | 456    | {'description': 'Support', 'code': '50544654'}
...

我可以将字典列转换为两个(或更多)列:

position_df['position'] = main_df['position'].apply(lambda x: dict(eval(x)))
position_df = position_df['position'].apply(pd.Series)
position_df.rename(columns={'des': 'position_name', 'code':'positionID'},inplace=True)

result = pd.concat([main_df, position_df], axis=1, join="inner")

我明白了

fiscalYear| prodID| position                                           | position_name         | posID
2020      | 123   | {'des': 'Customer Operations', 'code': '51254185'} | 'Customer Operations' | 51254185
2020      | 456   | {'des': 'Support', 'code': '50544654'}             | 'Support',            | 50544654
...

我创建了自定义函数并且只更改了输入,但我得到了 TypeError: 'DataFrame' object is not callable

这是我的函数和调用

    def dictionary_to_columns(dic_column,rename_col,df):
        temp_df = pd.DataFrame()
        # todo: # of items in the dictionary in dic_column
        temp_df['temporary'] = df[dic_column].apply(lambda x: dict(eval(x)))
        temp_df = temp_df['temporary'].apply(pd.Series)
        temp_df.rename(columns=rename_col,inplace=True)
        result = pd.concat([df, temp_df], axis=1, join="inner")
        return result

    main_df['position'] = main_df['position'].apply(dictionary_to_columns('position',{'des': 'name', 'code':'ID'},main_df))

我认为我在 return 语句中得到了错误。我在返回前打印了前 5 行,看起来还不错。有什么建议吗?

【问题讨论】:

  • apply 需要一个可调用对象...您的函数(dictionary_to_columns)返回一个数据帧...数据帧不是可调用对象

标签: python pandas dataframe dictionary typeerror


【解决方案1】:

找到解决方案后,我决定回答我自己的问题。也许其他人会使用它。

根据@Joran 的建议/建议,我返回一个 DataFrame,我将函数更改为:

    def dictionary_to_columns(dic_column, rename_col, df):
        temp_df = pd.DataFrame()
        # todo: # of items in the dictionary in dic_column
        temp_df['temporary'] = df[dic_column].apply(lambda x: dict(eval(x)))
        temp_df = temp_df['temporary'].apply(pd.Series)
        temp_df.rename(columns=rename_col, inplace=True)
        df = pd.concat([df, temp_df], axis=1, join="inner")

我没有分配给结果变量并返回,而是更改了原始 DataFrame。我认为最重要的是改变我的称呼方式:

dictionary_to_columns('position',{'des': 'name', 'code':'ID'},main_df)

它对我很有效。

【讨论】:

    【解决方案2】:

    将 dict 解压到列中就像从 apply 返回一个系列一样简单:

    df
    
       fiscalYear  prodID                                           position
    0        2020     123  {'description': 'Customer Operations', 'code':...
    1        2020     456     {'description': 'Support', 'code': '50544654'}
    
    df[['name', 'ID']] = df.apply(lambda row: pd.Series(row['position']), axis=1)
    
    df
    
       fiscalYear  prodID                                           position                 name        ID
    0        2020     123  {'description': 'Customer Operations', 'code':...  Customer Operations  51254185
    1        2020     456     {'description': 'Support', 'code': '50544654'}              Support  50544654
    

    【讨论】:

    • 我之前试过这个,但是没有用。我得到“ValueError:列必须与键长度相同”。无论如何,我解决了我的问题。见上面的解释
    猜你喜欢
    • 1970-01-01
    • 2012-10-14
    • 2018-01-08
    • 2018-02-23
    • 2020-05-31
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    相关资源
    最近更新 更多