gpt4 book ai didi

python - 为什么 pandas groupby().transform() 需要唯一索引?

转载 作者:太空狗 更新时间:2023-10-29 18:08:18 26 4
gpt4 key购买 nike

我想使用 groupby().transform() 对(排序的)数据集中的每个记录 block 进行自定义(累积)转换。除非我确保我有一个唯一的 key ,否则它不起作用。为什么?

这是一个玩具示例:

df = pd.DataFrame([[1,1],
[1,2],
[2,3],
[3,4],
[3,5]],
columns='a b'.split())
df['partials'] = df.groupby('a')['b'].transform(np.cumsum)
df

给出预期的:

     a   b   partials
0 1 1 1
1 1 2 3
2 2 3 3
3 3 4 4
4 3 5 9

但是如果 'a' 是一个键,一切都会出错:

df = df.set_index('a')
df['partials'] = df.groupby(level=0)['b'].transform(np.cumsum)
df

---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-146-d0c35a4ba053> in <module>()
3
4 df = df.set_index('a')
----> 5 df.groupby(level=0)['b'].transform(np.cumsum)

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/groupby.pyc in transform(self, func, *args, **kwargs)
1542 res = wrapper(group)
1543 # result[group.index] = res
-> 1544 indexer = self.obj.index.get_indexer(group.index)
1545 np.put(result, indexer, res)
1546

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/index.pyc in get_indexer(self, target, method, limit)
847
848 if not self.is_unique:
--> 849 raise Exception('Reindexing only valid with uniquely valued Index '
850 'objects')
851

Exception: Reindexing only valid with uniquely valued Index objects

如果您在分组之前选择“b”列,则会出现同样的错误,即。

df['b'].groupby(level=0).transform(np.cumsum)

但是如果你转换整个数据框,你可以让它工作,比如:

df.groupby(level=0).transform(np.cumsum)

甚至是单列数据框(而不是系列):

df.groupby(level=0)[['b']].transform(np.cumsum)

我觉得GroupBy-fu还有一些深奥的地方|我失踪了。有人可以让我直截了当吗?

最佳答案

这是一个错误,因为已在 pandas 中修复(当然是在 0.15.2 中,IIRC 在 0.14 中已修复),所以您不应再看到此异常。


作为解决方法,在早期的 pandas 中,您可以使用 apply :

In [10]: g = df.groupby(level=0)['b']

In [11]: g.apply(np.cumsum)
Out[11]:
a
1 1
1 3
2 3
3 4
3 9
dtype: int64

你可以将它分配给 df 中的列

In [12]: df['partial'] = g.apply(np.cumsum)

关于python - 为什么 pandas groupby().transform() 需要唯一索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16311793/

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