Pandas的问题与金额

2024-04-20 11:05:55 发布

您现在位置:Python中文网/ 问答频道 /正文

使用pandas0.11,在数据帧上设置和时,似乎有一个bug(或者至少是非直观的行为)。有什么建议吗

p = pandas.DataFrame({ 'x' : [1,2,3], 'y' : [1,2,3] })
sumOfP = p.sum() #Gives a Series of [6,6]. OK.
totals = pandas.DataFrame({ 'someOtherSeries' : [1,2])
totals['sumOfP'] = sumOfP #BAD! This is now [nan, nan]

我希望总数['sumOfP']是[6,6]。那为什么是楠,楠


Tags: of数据dataframepandasoknanbug建议
1条回答
网友
1楼 · 发布于 2024-04-20 11:05:55

因为它们在索引上对齐。仔细看看p.sum()

>>> sumOfP = p.sum()
>>> sumOfP
x    6
y    6
dtype: int64

这是一个由xy索引的Series,你想把它塞进一个索引为0和1的DataFrame的新列中。这很好,totals框架说,但是你没有告诉我在索引0和1的“sumoff”列中应该放什么,我不会猜。比较:

>>> p = pandas.DataFrame({ 0 : [1,2,3], 'y' : [1,2,3] })
>>> totals["sumOfP"] = p.sum()
>>> totals
   someOtherSeries  sumOfP
0                1       6
1                2     NaN

[2 rows x 2 columns]

如果要忽略索引,可以在需要时将值放入:

>>> totals["sumofP"] = sumOfP.values
>>> totals
   someOtherSeries  sumofP
0                1       6
1                2       6

[2 rows x 2 columns]

或者提前重置索引:

>>> sumOfP.reset_index(drop=True)
0    6
1    6
dtype: int64
>>> totals["sumOfP"] = sumOfP.reset_index(drop=True)
>>> totals
   someOtherSeries  sumOfP
0                1       6
1                2       6

[2 rows x 2 columns]

相关问题 更多 >