Pandas count values inside dataframe

≡放荡痞女 提交于 2021-02-20 05:00:32

问题


I have a dataframe that looks like this:

     A     B     C
1    1     8     3
2    5     4     3
3    5     8     1

and I want to count the values so to make df like this:

       total
1        2
3        2
4        1
5        2
8        2

is it possible with pandas?


回答1:


With np.unique -

In [332]: df
Out[332]: 
   A  B  C
1  1  8  3
2  5  4  3
3  5  8  1

In [333]: ids, c = np.unique(df.values.ravel(), return_counts=1)

In [334]: pd.DataFrame({'total':c}, index=ids)
Out[334]: 
   total
1      2
3      2
4      1
5      2
8      2

With pandas-series -

In [357]: pd.Series(np.ravel(df)).value_counts().sort_index()
Out[357]: 
1    2
3    2
4    1
5    2
8    2
dtype: int64



回答2:


You can also use stack() and groupby()

df = pd.DataFrame({'A':[1,8,3],'B':[5,4,3],'C':[5,8,1]})
print(df)
    A   B   C
0   1   5   5
1   8   4   8
2   3   3   1

df1 = df.stack().reset_index(1)

df1.groupby(0).count()

    level_1
0   
1   2
3   2
4   1
5   2
8   2



回答3:


Other alternative may be to use stack, followed by value_counts then, result changed to frame and finally sorting the index:

count_df = df.stack().value_counts().to_frame('total').sort_index()
count_df

Result:

     total
1      2
3      2
4      1
5      2
8      2



回答4:


using np.unique(, return_counts=True) and np.column_stack():

pd.DataFrame(np.column_stack(np.unique(df, return_counts=True)))

returns:

   0  1
0  1  2
1  3  2
2  4  1
3  5  2
4  8  2


来源:https://stackoverflow.com/questions/47963928/pandas-count-values-inside-dataframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!