同时将多个数据框作为参数传递给Python用户函数

我正在创建此功能:

    def stand_col_names(*df_to_stand):
        '''function that allow you to lowercase dataframes columns'''
        df_to_stand.columns = df_to_stand.columns.str.lower()
        return df_to_stand

如您所见,我的目标是同时传递多个数据帧以转换列名。像这样:

df1,df2,df3,df4 = stand_col_names(df1,df4)

我不想要一个只接受一个参数的函数,因此只写四行,每个数据帧一行。

当我运行它时,出现以下错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-20-c4c8e2ccc0f3> in <module>
----> 1 df_target_pm,df_target_sp=stand_col_names(df_target_pm,df_target_sp)

<ipython-input-18-65eb087bc145> in stand_col_names(*df_to_stand)
  1 def stand_col_names(*df_to_stand):
  2     '''function that allow you to lowercase dataframes columns'''
----> 3     df_to_stand.columns = df_to_stand.columns.str.lower()
  4     return df_to_stand

AttributeError: 'tuple' object has no attribute 'columns'

能帮我吗?

gaopin586 回答:同时将多个数据框作为参数传递给Python用户函数

实际上,由于您正在修改DataFrame的属性,因此根本不需要执行任何返回操作:

def stand_col_names(*df_to_stand):
    '''function that allow you to lowercase dataframes columns'''
    for df in df_to_stand:
        df.columns = df.columns.str.lower()

# to call,just do:
stand_col_names(df1,df2,df3,df4)

但是总的来说,我同意@ALollz的评论。此函数应用于单个Dataframe,并且循环应存在于外部:

def stand_col_names(df):
    df.columns = df.columns.str.lower()

for df in (df1,df4):
    stand_col_names(df)
,
def stand_col_names(*dataframes):
    for df in dataframes:
        df.columns = df.columns.str.lower()

    return dataframes

一些解释。 *运算符(实际上我不知道在Python中通常叫什么,但在其他地方称为“ spread”运算符)将所有参数收集到一个元组中。 for循环在元组中迭代并更改其值。然后返回元组。

警告一下,这会改变原始数据框的位置,您可能不希望这样做。如果要保留原始数据框的大写列,则需要遍历集合,将副本复制到第二个元组,然后返回第二个元组。

本文链接:https://www.f2er.com/3136466.html

大家都在问