为什么我不能分配给我的一些Pandas DataFrame? [英] Why can't I assign to part of my Pandas DataFrame?
问题描述
我很困惑,为什么以下 pandas
没有成功地将列A的最后两个值分配给列B的前两个条目:
I'm confused why the following pandas
does not successfully assign the last two values of column A to the first two entries of column B:
df = pd.DataFrame({'A': [1, 2, 3, 4, 5, 6, 7], 'B': [10, 20, 30, 40, 50, 60, 70]})
df = df.join(pd.DataFrame({'C': ['a', 'b', 'c', 'd', 'e', 'f', 'g']}))
df['B2'] = df.B.shift(2)
df[:2].B2 = list(df[-2:].A)
令人困惑的是,在(显然)相当于真正的应用程序,它似乎工作(并产生一些奇怪的行为)。
What's perplexing to me is that in an (apparently) equivalent "real" application, it does appear to work (and to generate some strange behavior).
为什么最终配置无法更改数据帧中两个条目的值?
Why does the final assignment fail to change the values of the two entries in the dataframe?
推荐答案
它可以工作,这就是为什么它的阴险,看到这里: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
通常使用多重类型的框架,这取决于当它可以工作时的构造(例如如果您一次创建它,我认为它将始终工作)。由于您在(通过连接)之后创建它,它取决于基本的numpy视图创建机制。
Generally with multi-dtyped frames it depends on the construction of when it would work (e.g. if you create it all at once, I think it will always work). Since you are creating it after (via join) it is dependent on the underlying numpy view creation mechanisms.
永远不会分配这样,使用 loc
don't ever ever ever assign like that, use loc
df.loc[:2,'B2'] = ....
这篇关于为什么我不能分配给我的一些Pandas DataFrame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!