我为什么要在 pandas 中制作数据框的副本 [英] why should I make a copy of a data frame in pandas

查看:25
本文介绍了我为什么要在 pandas 中制作数据框的副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从父数据帧中选择子数据帧时,我注意到一些程序员使用 .copy() 方法制作数据帧的副本.例如,

When selecting a sub dataframe from a parent dataframe, I noticed that some programmers make a copy of the data frame using the .copy() method. For example,

X = my_dataframe[features_list].copy()

...而不仅仅是

X = my_dataframe[features_list]

他们为什么要复制数据框?如果我不制作副本会怎样?

Why are they making a copy of the data frame? What will happen if I don't make a copy?

推荐答案

这扩展了 Paul 的回答.在 Pandas 中,索引 DataFrame 会返回对初始 DataFrame 的引用.因此,更改子集将更改初始 DataFrame.因此,如果您想确保初始 DataFrame 不应该更改,则需要使用副本.考虑以下代码:

This expands on Paul's answer. In Pandas, indexing a DataFrame returns a reference to the initial DataFrame. Thus, changing the subset will change the initial DataFrame. Thus, you'd want to use the copy if you want to make sure the initial DataFrame shouldn't change. Consider the following code:

df = DataFrame({'x': [1,2]})
df_sub = df[0:1]
df_sub.x = -1
print(df)

你会得到:

x
0 -1
1  2

相比之下,以下内容保持 df 不变:

In contrast, the following leaves df unchanged:

df_sub_copy = df[0:1].copy()
df_sub_copy.x = -1

这篇关于我为什么要在 pandas 中制作数据框的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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