【问题标题】:adding a column to dataframe's copy without changing the original dataframe在不更改原始数据框的情况下向数据框的副本添加一列
【发布时间】:2018-07-31 06:16:18
【问题描述】:

我有熊猫数据框。我调用一个函数 add_column,发送数据帧的副本。为什么原始数据框会发生变化(添加了额外的列)?

new_df = add_column(ori_df.copy(),"nameofnewcol", col) 

def add_column(df, name_col, col):
    df[name_col] = pd.Series(np.asarray(col), index= df.index)
    return df

问题是 ori_df 也有额外的列。 根据文档,深层副本默认设置为 true。有人能说出为什么会这样吗?

【问题讨论】:

  • 在我的系统中运行良好..!再检查一遍

标签: python pandas dataframe copy deep-copy


【解决方案1】:

它应该可以正常工作。如果没有,请尝试分配一个虚拟变量并将该变量传递给函数

df_dummy=ori_df
new_df=add_column(df_dummy,"nameofnewcol",col)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多