Pandas 数据帧内的计数值
我有一个如下所示的数据帧:Pandas 数据帧内的计数值,pandas,dataframe,Pandas,Dataframe,我有一个如下所示的数据帧: A B C 1 1 8 3 2 5 4 3 3 5 8 1 total 1 2 3 2 4 1 5 2 8 2 我想计算数值,使df如下: A B C 1 1 8 3 2 5 4 3 3 5 8 1
A B C
1 1 8 3
2 5 4 3
3 5 8 1
total
1 2
3 2
4 1
5 2
8 2
我想计算数值,使df如下:
A B C
1 1 8 3
2 5 4 3
3 5 8 1
total
1 2
3 2
4 1
5 2
8 2
熊猫有可能吗?-
使用熊猫系列-
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
与-
使用熊猫系列-
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
您还可以使用
stack()
和groupby()
您还可以使用
stack()
和groupby()
其他替代方法可能是使用
堆栈
,然后使用值_计数
,然后将结果更改为帧,最后对索引进行排序:
count_df = df.stack().value_counts().to_frame('total').sort_index()
count_df
结果:
total
1 2
3 2
4 1
5 2
8 2
其他替代方法可能是使用
堆栈
,然后使用值_计数
,然后将结果更改为帧,最后对索引进行排序:
count_df = df.stack().value_counts().to_frame('total').sort_index()
count_df
结果:
total
1 2
3 2
4 1
5 2
8 2
使用np.unique(,return\u counts=True)
和np.column\u stack()
返回:
0 1
0 1 2
1 3 2
2 4 1
3 5 2
4 8 2
使用np.unique(,return\u counts=True)
和np.column\u stack()
返回:
0 1
0 1 2
1 3 2
2 4 1
3 5 2
4 8 2