将 Pandas DataFrame 传递给函数的最佳实践

Boo*_*oom 7 python function mutable dataframe pandas

我目前正在使用一些 DataFrame,并希望使我的代码模块化。这需要将数据帧传递给函数。我知道 DataFrame 的可变性质以及将可变实例传递给函数时的一些“陷阱”。DataFrames 的功能是否有最佳实践?我应该在函数内复制一份然后将其传回吗?或者我应该在函数内对 df 进行更改并返回 None ?

选项 1 还是选项 2 更好?下面是传达这个想法的基本代码:

选项1:

def test(df):
    df['col1'] = df['col1']+1
    return None

test(df)
Run Code Online (Sandbox Code Playgroud)

选项2:

def test(main_df):
    df = main_df.copy()
    df['col1'] = df['col1']+1
    return df 

main_df = test(main_df)
Run Code Online (Sandbox Code Playgroud)

小智 3

我使用了很多DataFrame.pipe来组织我的代码,所以我要说选项 2.pipe接受并返回一个 DataFrame,您可以将多个步骤链接在一起。

def step1(main_df):
    df = main_df.copy()
    df['col1'] = df['col1']+1
    return df 

def step2(main_df):
    df = main_df.copy()
    df['col1'] = df['col1']+1
    return df 

def setp3(main_df):
    df = main_df.copy()
    df['col1'] = df['col1']+1
    return df 

main_df = (main_df.pipe(step1)
    .pipe(step2)
    .pipe(step3)
)
Run Code Online (Sandbox Code Playgroud)