Python和Pandas:将使用许多数据框副本影响代码的性能?

2024-03-28 20:49:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一些数据分析,数据在熊猫DataFramedf。你知道吗

我在df上定义了几个函数来执行进程。你知道吗

出于封装目的,我定义如下函数:

def df_process(df):
    df=df.copy()
    # do some process work on df
    return df

在Jupyter笔记本中,我将函数用作

df = df_process(df)

使用df.copy()的原因是,否则,无论是否重新分配,原始的df都会被修改。(见Python & Pandas: How to return a copy of a dataframe?

我的问题是:

  1. 这里使用df=df.copy()合适吗?如果不是,应该如何定义函数处理数据?

  2. 由于我使用了几个这样的数据处理函数,它会影响我的程序的性能吗?多少钱?


Tags: 数据函数目的dataframedfreturn定义进程
1条回答
网友
1楼 · 发布于 2024-03-28 20:49:08

最好是:

def df_process(df):
    # do some process work on df

def df_another(df):
    # other processing

def df_more(df):
    # yet more processing

def process_many(df):
    for frame_function in (df_process, df_another, df_more):
        df_copy = df.copy()
        frame_function(df_copy)
        # emit the results to a file or screen or whatever

这里的关键是,如果您必须制作一个副本,只制作一个,处理它,将结果存储在某个地方,然后通过重新分配df_copy来处理它。你的问题没有提到为什么你要挂在处理过的副本,所以这假设你不需要。你知道吗

相关问题 更多 >