按索引+列按 pandas 分组 [英] Group by index + column in pandas
本文介绍了按索引+列按 pandas 分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含列的数据框
I have a dataframe that has the columns
- user_id
- item_bought
这里的user_id是df的索引.我想同时按user_id和item_bought分组,并为用户获取明智的商品计数.我该怎么做.
Here user_id is the index of the df. I want to group by both user_id and item_bought and get the item wise count for the user. How do I do that.
谢谢
推荐答案
从版本 0.20.1 更简单:
作为 by 参数传递给 DataFrame.groupby()的字符串现在可以引用列名称或索引级别名称
Strings passed to DataFrame.groupby() as the by parameter may now reference either column names or index level names
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])
df = pd.DataFrame({'A': [1, 1, 1, 1, 2, 2, 3, 3],
'B': np.arange(8)}, index=index)
print (df)
A B
first second
bar one 1 0
two 1 1
baz one 1 2
two 1 3
foo one 2 4
two 2 5
qux one 3 6
two 3 7
print (df.groupby(['second', 'A']).sum())
B
second A
one 1 2
2 4
3 6
two 1 4
2 5
3 7
这篇关于按索引+列按 pandas 分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文