怎样复制得到一个一模一样的dataframe?

我有一个dataframe a=pd.DataFrame({"A":[1,2,3,4,5,6]})
怎样复制得到另一个一模一样的dataframe b?
dataframe.copy()中deep是True和False有什么区别?

import pandas as pd
a=pd.DataFrame({"A":[1,2,3,4,5,6]})
b=a.copy()
print("a",id(a),a.columns)
print("b",id(b),b.columns)
b.columns=["B"]
print("a",id(a),a.columns)
print("b",id(b),b.columns)

结果为:
a 35432320 Index(['A'], dtype='object')
b 99956440 Index(['A'], dtype='object')
a 35432320 Index(['A'], dtype='object')
b 99956440 Index(['B'], dtype='object')
是不是这样就生成了一个新的对象b与a的内容一模一样?

阅读 14.8k
2 个回答

用copy.deepcopy吧。

    Parameters
            ----------
    deep : boolean or string, default True
        Make a deep copy, including a copy of the data and the indices.
        With ``deep=False`` neither the indices or the data are copied.

        Note that when ``deep=True`` data is copied, actual python objects
        will not be copied recursively, only the reference to the object.
        This is in contrast to ``copy.deepcopy`` in the Standard Library,
        which recursively copies object data.

要先了解DataFrame.copy()默认就是 deep 模式。所以。。。。你的标题不太准确。

推荐问题