为什么插入到复制数据框中的新列也会被添加到原始数据框中? [英] Why the inserted new column to a copied dataframe will be added to the original dataframe too?

查看:45
本文介绍了为什么插入到复制数据框中的新列也会被添加到原始数据框中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否让我知道为什么将新列c添加到原始数据框中,即df_old?

Could you please let me know why the new column c is added to the original dataframe i.e., df_old?

df_old = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
df_new=df_old
df_new['c']=[5,6]
print('Old:')
print(df_old)
print('New:')
print(df_new)

输出:

Old:
   a  b  c
0  1  3  5
1  2  4  6
New:
   a  b  c
0  1  3  5
1  2  4  6

实际上,我需要保留原始数据框:

In fact, I need to preserve the original dataframe as it was:

   a  b  
0  1  3  
1  2  4  

预先感谢

推荐答案

使用

Use assign which creates a copy of the old dataframe:

df_old = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
df_new = df_old.assign(c=[5,6])
print(df_old)
print(df_new)

输出:

   a  b
0  1  3
1  2  4
   a  b  c
0  1  3  5
1  2  4  6

这篇关于为什么插入到复制数据框中的新列也会被添加到原始数据框中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆