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

查看:43
本文介绍了我为什么要在 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.

为什么要复制数据框?如果我不复制怎么办?

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天全站免登陆