nic*_*_eu 30 python pandas chained-assignment
有没有一种简单的方法可以检查两个数据框是不同的副本还是不涉及操作的相同基础数据的视图?我试图抓住每一个生成的时间,并且考虑到规则似乎有多特殊,我想要一种简单的测试方法.
例如,我认为"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
Run Code Online (Sandbox Code Playgroud)
其他答案我已经抬头试图给出规则,但似乎不一致,也不回答如何测试的问题:
当然: - http://pandas.pydata.org/pandas-docs/stable/indexing.html#returning-a-view-versus-a-copy
更新:下面的评论似乎回答了这个问题 - 查看df.values.base属性而不是df.values属性,以及对df._is_copy属性的引用(尽管后者可能是非常糟糕的形式,因为它是内部的).
nic*_*_eu 22
来自HYRY和Marius的评论在评论中!
可以通过以下方式检查:
测试values.base属性的等价性而不是values属性,如:
df.values.base is df2.values.base而不是df.values is df2.values.
_is_view属性(df2._is_view是True).感谢大家!
我已经用pandas 1.0.1详细说明了这个例子。不仅有一个布尔_is_view属性,而且_is_copy它可以是None原始数据帧的或引用:
df = pd.DataFrame([[1,2,3,4],[5,6,7,8]], index = ['row1','row2'],
columns = ['a','b','c','d'])
df2 = df.iloc[0:2, :]
df3 = df.loc[df['a'] == 1, :]
# df is neither copy nor view
df._is_view, df._is_copy
Out[1]: (False, None)
# df2 is a view AND a copy
df2._is_view, df2._is_copy
Out[2]: (True, <weakref at 0x00000236635C2228; to 'DataFrame' at 0x00000236635DAA58>)
# df3 is not a view, but a copy
df3._is_view, df3._is_copy
Out[3]: (False, <weakref at 0x00000236635C2228; to 'DataFrame' at 0x00000236635DAA58>)
Run Code Online (Sandbox Code Playgroud)
因此,检查这两个属性不仅可以告诉您是否正在处理视图,还可以告诉您是否有副本或“原始”DataFrame。
另请参阅此线程以了解为什么您不能总是预测您的代码是否会返回视图的讨论。
| 归档时间: |
|
| 查看次数: |
9256 次 |
| 最近记录: |