gpt4 book ai didi

python - Pandas View 与副本 : the docs says "nobody knows"?

转载 作者:太空狗 更新时间:2023-10-30 00:43:33 37 4
gpt4 key购买 nike

StackOverflow 上有很多关于链式索引以及特定操作是生成 View 还是副本的问题。 (例如,herehere )。我仍然没有完全理解,但令人惊奇的是官方文档说“没人知道”。 (!?!??) 这是文档中的示例;你能告诉我他们是真的这么想,还是只是轻率?

来自 https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#why-does-assignment-fail-when-using-chained-indexing

def do_something(df):
foo = df[['bar', 'baz']] # Is foo a view? A copy? Nobody knows!
# ... many lines here ...
foo['quux'] = value # We don't know whether this will modify df or not!
return foo

是认真的吗?对于那个具体的例子,“没人知道”真的是真的吗?这是不确定的吗?这真的会在两个不同的数据帧上表现不同吗?规则真的那么复杂?或者这家伙的意思是有一个明确的答案,但大多数人都不知道?

最佳答案

我想我可以展示一些东西来阐明您的情况,在您的示例中,最初它将是一个 View ,但是一旦您尝试通过添加列进行修改,它就会变成一个副本。您可以通过查看属性 ._is_view 来测试它:

In [29]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
def doSomething(df):
a = df[['b','c']]
print('before ', a._is_view)
a['d'] = 0
print('after ', a._is_view)

doSomething(df)
df

before True
after False
Out[29]:
a b c
0 0.108790 0.580745 1.820328
1 1.066503 -0.238707 -0.655881
2 -1.320731 2.038194 -0.894984
3 -0.962753 -3.961181 0.109476
4 -1.887774 0.909539 1.318677

所以在这里我们可以看到最初 a 是原始 df 的原始子部分的 View ,但是一旦你向它添加一个列,这就不再正确了,我们可以看到原始df没有修改。

关于python - Pandas View 与副本 : the docs says "nobody knows"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39101933/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com