【问题标题】:Pandas - inplace, view, copy confusionPandas - 就地、查看、复制混乱
【发布时间】:2017-05-08 20:24:57
【问题描述】:

我遇到了 Pandas 数据框的问题。 似乎 Pandas/Python 在我的代码中的某处生成了 DF 的副本,而不是对原始 DF 进行修改。

在下面的代码中,“update_df”仍然看到带有“file_exists”列的 DF,该列应该已被前面的函数删除。

主要:

if __name__ == '__main__':
    df_main = load_df()
    clean_df2(df_main)
    update_df(df_main, image_path_main)
    .....

clean_df2

def clean_df2(df): #remove non-existing files from DF
    df['file_exists'] = True # add column, set all to True?
    .....
    df = df[df['file_exists'] != False] #Keep only records that exist
    df.drop('file_exists', 1, inplace=True)  # delete the temporary column
    df.reset_index(drop=True, inplace = True)  # reindex if source has gaps

update_df:

def update_df(df, image_path): #add DF rows for files not yet in DF
    print(df)
    ....

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我想当你这样做时:

    df = df[df['file_exists'] != False]
    

    您已创建原始 df 的副本。

    要使其正常工作,您可以将函数更改为:

    def clean_df2(df): #remove non-existing files from DF
        df['file_exists'] = True # add column, set all to True?
        .....
        return df
    

    当您调用 clean_df2(df) 时,请执行以下操作:

    df = clean_df2(df)
    

    【讨论】:

    • 更好的是,将行改为df.drop(df['file_exits'] != False, inplace=True)
    • 这是另一种选择。可以在函数内部轻松制作副本。返回最终的 df 可能是更安全的选择。
    • 我想,但出于内存原因,您通常希望避免复制数据帧。
    猜你喜欢
    • 2021-08-24
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多