有没有一种简单的方法来检查两个数据帧是否是不涉及操作的相同基础数据的不同副本或视图?我试图掌握每个规则的生成时间,并且考虑到规则看起来有多么特殊,我想要一种简单的测试方法。
例如,我认为“id(df.values)”在不同视图中是稳定的,但它们似乎并非如此:
# Make two data frames that are views of same data.
df = pd.DataFrame([[1,2,3,4],[5,6,7,8]], index = ['row1','row2'],
columns = ['a','b','c','d'])
df2 = df.iloc[0:2,:]
# Demonstrate they are views:
df.iloc[0,0] = 99
df2.iloc[0,0]
Out[70]: 99
# Now try and compare the id on values attribute
# Different despite being views!
id(df.values)
Out[71]: 4753564496
id(df2.values)
Out[72]: 4753603728
# And we can of course compare df and df2
df is df2
Out[73]: False
我查过的其他答案试图给出规则,但似乎不一致,而且也没有回答如何测试的问题:
Pandas 使用什么规则来生成视图和副本? https://stackoverflow.com/questions/23296282/what-rules-does-pandas-use-to-generate-a-view-vs-a-copy
Pandas:子索引数据帧:副本与视图 https://stackoverflow.com/questions/17960511/pandas-subindexing-dataframes-copies-vs-views
了解 pandas 数据帧索引 https://stackoverflow.com/questions/14192741/understanding-pandas-dataframe-indexing
Pandas 中的重新分配:复制还是查看? https://stackoverflow.com/questions/22537112/re-assignment-in-pandas-copy-or-view
而且当然:
-http://pandas.pydata.org/pandas-docs/stable/indexing.html#returning-a-view-versus-a-copy http://pandas.pydata.org/pandas-docs/stable/indexing.html#returning-a-view-versus-a-copy
UPDATE:下面的评论似乎回答了这个问题——看看df.values.base
属性而不是df.values
属性可以做到这一点,就像对df._is_copy
属性(尽管后者可能是非常糟糕的形式,因为它是内部的)。