在pandas中,我可以深度复制包含其索引和列的DataFrame吗?

时间:2021-01-02 08:01:04

First, I create a DataFrame

首先,我创建一个DataFrame

In [61]: import pandas as pd
In [62]: df = pd.DataFrame([[1], [2], [3]])

Then, I deeply copy it by copy

然后,我通过复制深深地复制它

In [63]: df2 = df.copy(deep=True)

Now the DataFrame are different.

现在DataFrame是不同的。

In [64]: id(df), id(df2)
Out[64]: (4385185040, 4385183312)

However, the index are still the same.

但是,指数仍然相同。

In [65]: id(df.index), id(df2.index)
Out[65]: (4385175264, 4385175264)

Same thing happen in columns, is there any way that I can easily deeply copy it not only values but also index and columns?

在列中发生同样的事情,有没有什么方法可以轻松地将其复制到值,还有索引和列?

2 个解决方案

#1


25  

Latest version of Pandas does not have this issue anymore

最新版本的熊猫不再有这个问题了

  import pandas as pd
  df = pd.DataFrame([[1], [2], [3]])

  df2 = df.copy(deep=True)

  id(df), id(df2)
  Out[3]: (136575472, 127792400)

  id(df.index), id(df2.index)
  Out[4]: (145820144, 127657008)

#2


11  

I wonder whether this is a bug in pandas... it's interesting because Index/MultiIndex (index and columns) are in some sense supposed to be immutable (however I think these should be copies).

我想知道这是否是熊猫中的一个错误......这很有趣,因为Index / MultiIndex(索引和列)在某种意义上应该是不可变的(但我认为这些应该是副本)。

For now, it's easy to create your own method, and add it to DataFrame:

现在,可以轻松创建自己的方法,并将其添加到DataFrame:

In [11]: def very_deep_copy(self):
    return pd.DataFrame(self.values.copy(), self.index.copy(), self.columns.copy())

In [12]: pd.DataFrame.very_deep_copy = very_deep_copy

In [13]: df2 = df.very_deep_copy()

As you can see this will create new objects (and preserve names):

如您所见,这将创建新对象(并保留名称):

In [14]: id(df.columns)
Out[14]: 4370636624

In [15]: id(df2.columns)
Out[15]: 4372118776

#1


25  

Latest version of Pandas does not have this issue anymore

最新版本的熊猫不再有这个问题了

  import pandas as pd
  df = pd.DataFrame([[1], [2], [3]])

  df2 = df.copy(deep=True)

  id(df), id(df2)
  Out[3]: (136575472, 127792400)

  id(df.index), id(df2.index)
  Out[4]: (145820144, 127657008)

#2


11  

I wonder whether this is a bug in pandas... it's interesting because Index/MultiIndex (index and columns) are in some sense supposed to be immutable (however I think these should be copies).

我想知道这是否是熊猫中的一个错误......这很有趣,因为Index / MultiIndex(索引和列)在某种意义上应该是不可变的(但我认为这些应该是副本)。

For now, it's easy to create your own method, and add it to DataFrame:

现在,可以轻松创建自己的方法,并将其添加到DataFrame:

In [11]: def very_deep_copy(self):
    return pd.DataFrame(self.values.copy(), self.index.copy(), self.columns.copy())

In [12]: pd.DataFrame.very_deep_copy = very_deep_copy

In [13]: df2 = df.very_deep_copy()

As you can see this will create new objects (and preserve names):

如您所见,这将创建新对象(并保留名称):

In [14]: id(df.columns)
Out[14]: 4370636624

In [15]: id(df2.columns)
Out[15]: 4372118776