Pandas 面板:复制 vs. 视图

3

基本上,如果我想在原始数据框中更改数据,我总是需要使用.loc[]。但考虑以下情况

>>> import pandas as pd
>>> from scipy import random
>>> from numpy import arange

>>> T, N = 4, 5
>>> TIndex = arange(0, T)
>>> FIndex = arange(0, N)

>>> wp = pd.Panel(items=['A', 'w', 'l', 'a', 'x', 'X', 'd', 'profit'],
...               major_axis=TIndex, minor_axis=FIndex)
>>> wp.loc['a', 0, 0] = 0 
>>> df = wp.loc[0, 'a']
>>> df.loc[0, 'a'] = 'test'
>>> df.loc[0, 'a']
Out[379]: 'test'
>>> wp.loc['a', 0, 0]
Out[380]: 0

我错在哪里了?

同时,没有抛出SettingWithCopyWarning。当我在数据框级别犯这些错误时,通常会出现这种情况。这非常令人恼火。


1
TN是什么?最好提供一个自包含的例子。 - logc
一些正整数。我已经添加了一些值。:) - FooBar
你使用的是哪个版本?你的示例在 df = wp.loc[0, 'a'] 处抛出了 KeyError 错误。我这里没有 0 在你的项目中。 - TomAugspurger
1个回答

2

我可以通过在调用loc时按标签选择来修改DataFrame和原始Panel。文档说loc 严格限制于标签,所以我不确定您发布的代码是否能够正常工作:当将示例粘贴到IPython控制台中时,我得到了一个KeyError:'the label [0] is not in the [items]'

而不是

df = wp.loc[0, 'a']

做;干;执行
df = wp.loc['a']

然后使用iloc和整数索引进行修改:
In [3]: df
Out[3]:
    0   1   2   3   4
0   0 NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN
3 NaN NaN NaN NaN NaN

[4 rows x 5 columns]

In [4]: df.iloc[0, 0] = 'test'

In [5]: df
Out[5]:
      0    1    2    3    4
0  test  NaN  NaN  NaN  NaN
1   NaN  NaN  NaN  NaN  NaN
2   NaN  NaN  NaN  NaN  NaN
3   NaN  NaN  NaN  NaN  NaN

[4 rows x 5 columns]

In [6]: wp.loc['a']
Out[6]:
      0    1    2    3    4
0  test  NaN  NaN  NaN  NaN
1   NaN  NaN  NaN  NaN  NaN
2   NaN  NaN  NaN  NaN  NaN
3   NaN  NaN  NaN  NaN  NaN

[4 rows x 5 columns]

到目前为止很好 - 我需要检查我的混乱哪一部分在为了 SO 的工作示例而“变笨”的过程中丢失了。如果可以,我有一个后续问题:如果 df 不应该基于“项目”是切片,而是基于主轴,那么我能否安全地影响 df = wp.major_xs(0) 并将值设置到 wp 上? - FooBar
切片面板 可以 给出视图,因此应该进行标记;这是一个错误,因为设置查看的数据框应该引发 SettingWithCopy:https://github.com/pydata/pandas/issues/7184 - Jeff
@FooBar:就我所测试的情况来看,不行,你不能通过主轴设置值。无论这是否是Pandas的正确行为,我很抱歉我不知道。 - logc
如果你想通知一个不是答案所有者或原帖作者的用户,那么你必须在其用户名前加上 @ 符号,例如:@Jeff。我没有在 FooBar 前面加上它是因为同一时间只能通知一个用户。 - logc
@FooBar 是的,“bar=wp.loc[...]”是Panel的一个切片(根据“.loc”的参数,它可以是panel、dataframe、series或标量)。你不应该对切片进行赋值(“SettingWithCopy”警告的原因就在于此,但请参见这里:http://pandas-docs.github.io/pandas-docs-travis/indexing.html#indexing-view-versus-copy;甚至有时候无法检测到用户正在做什么,这只是一种启发式方法。 - Jeff
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接