为什么pandas groupby().transform() 需要唯一索引? [英] Why does pandas groupby().transform() require a unique index?

查看:69
本文介绍了为什么pandas groupby().transform() 需要唯一索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to use groupby().transform() to do a custom (cumulative) transform of each block of records in a (sorted) dataset. Unless I ensure I have a unique key, it doesn't work. Why?

这是一个玩具示例:

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' 是一个键,那么一切都会出错:

but if 'a' is a key, it all goes wrong:

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' 也会出现同样的错误,即.

Same error if you select column 'b' before grouping, ie.

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

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

but you can make it work if you transform the entire dataframe, like:

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

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

or even a one-column dataframe (rather than series):

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

我觉得 GroupBy-fu 仍有一些深层的部分丢失的.有人可以让我直截了当吗?

I feel like there's some still some deep part of GroupBy-fu that I'm missing. Can someone set me straight?

推荐答案

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

This was a bug, since fixed in pandas (certainly in 0.15.2, IIRC it was fixed in 0.14), so you should no longer see this exception.

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

As a workaround, in earlier pandas you can use 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 中的列

and you can assign this to a column in df

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

这篇关于为什么pandas groupby().transform() 需要唯一索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆