简体   繁体   English

按熊猫数据框的索引对所有列的值进行分组

[英]Grouping the values of all columns by index of a pandas dataframe

I want to basically build a distribution of total no. 我想基本建立总分配。 of videos a user has watched. 用户观看的视频数量。 Watch is signified by 1 else 0. Users are index of the data frame. 监视用1否则0表示。用户是数据帧的索引。

Assume the data is like this: 假设数据是这样的:

A   B   C
User1   1   1   0
User2   0   1   0
User3   1   0   1

I want for each use a count of all the 1 in that row. 我希望每次使用该行中所有1的计数。

I am doing something like this but it doesn't seem to work. 我正在做这样的事情,但似乎没有用。 I dont want to use some applymap function as that seem to be slow. 我不想使用某些applymap函数,因为这似乎很慢。

d.groupby(d.index).sum(axis=1)

Gives error that axis not recognized 给出轴无法识别的错误

If you have duplicates in index, you can use groupby with double sum : 如果索引中有重复项,则可以将groupby与double sum一起使用:

print (df)
       A  B  C
User1  1  1  0
User1  1  1  1
User2  0  1  0
User3  1  0  1

print (df.groupby(df.index).sum().sum(1))
User1    5
User2    1
User3    2
dtype: int64

If there are no duplicates, use only sum - Psidom comment : 如果没有重复项,请仅使用sum -Psidom注释

df.sum(axis=1)

EDIT: 编辑:

import matplotlib.pyplot as plt

df.sum(axis=1).plot.hist()
plt.show()

图形

Use the transpose method of the DataFrame. 使用DataFrame的转置方法。

In [38]: d = pd.DataFrame({'A':[1,0,1],'B':[1,1,0],'C':[0,0,1]},index=['User1','User2','User3'])

In [39]: d
Out[39]:
       A  B  C
User1  1  1  0
User2  0  1  0
User3  1  0  1

In [40]: d.transpose()
Out[40]:
   User1  User2  User3
A      1      0      1
B      1      1      0
C      0      0      1

In [41]: d.transpose().sum()
Out[41]:
User1    2
User2    1
User3    2
dtype: int64

Or, as Psidom suggested, sum the columns of your DataFrame. 或者,按照Psidom的建议,对DataFrame的列求和。

In [55]: d.sum(axis=1)
Out[55]:
User1    2
User2    1
User3    2
dtype: int64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM