我已经从 R 切换到 pandas。当我做类似的事情时,我经常会收到 SettingWithCopyWarnings
df_a = pd.DataFrame({'col1': [1,2,3,4]})
# Filtering step, which may or may not return a view
df_b = df_a[df_a['col1'] > 1]
# Add a new column to df_b
df_b['new_col'] = 2 * df_b['col1']
# SettingWithCopyWarning!!
我想我理解了这个问题,但我很乐意了解我做错了什么。在给定的示例中,未定义df_b
是否是df_a
上的 View 。因此,分配给 df_b
的效果还不清楚:它会影响 df_a
吗?可以通过在过滤时显式制作副本来解决问题:
df_a = pd.DataFrame({'col1': [1,2,3,4]})
# Filtering step, definitely a copy now
df_b = df_a[df_a['col1'] > 1].copy()
# Add a new column to df_b
df_b['new_col'] = 2 * df_b['col1']
# No Warning now
我认为我缺少一些东西:如果我们永远无法真正确定我们是否创建了一个 View ,那么 View 有什么用?来自 Pandas 文档 ( http://pandas-docs.github.io/pandas-docs-travis/indexing.html?highlight=view#indexing-view-versus-copy )
Outside of simple cases, it’s very hard to predict whether it [getitem] will return a view or a copy (it depends on the memory layout of the array, about which pandas makes no guarantees)
对于不同的索引方法可以找到类似的警告。
我发现在我的代码中散布 .copy() 调用非常麻烦且容易出错。我是否使用了错误的样式来操作我的 DataFrame?还是性能提升如此之高以至于明显的尴尬是合理的?
最佳答案
好问题!
简短的回答是:这是正在修复的 pandas 中的一个缺陷。
您可以找到关于 the problem here 性质的更长讨论,但主要的收获是我们现在正在转向“写时复制”行为,在这种行为中,任何时候切片,您都会得到一个新副本,而您永远不必考虑 View 。修复将很快通过此 refactoring project. 进行我实际上试图直接修复它 ( see here ),但它在当前架构中不可行。
事实上,我们会将 View 保留在后台——当它们可以提供时,它们使 pandas super 内存高效和快速——但我们最终会向用户隐藏它们,因此,从用户的角度来看,如果你对 DataFrame 进行切片、索引或剪切,您得到的实际上是一个新副本。
(这是通过在用户仅读取数据时创建 View 来实现的,但是每当使用赋值操作时, View 将在赋值发生之前转换为副本。)
最好的猜测是修复会在一年内完成——与此同时,恐怕可能需要一些 .copy()
,抱歉!
关于python - 如果未定义索引操作返回 View 还是副本, Pandas 的观点是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34884536/