具有多列数据帧中的值计数的单列 [英] Single column with value counts from multiple column dataframe

查看:34
本文介绍了具有多列数据帧中的值计数的单列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用熊猫将多列的频率求和.列的数量可以在2至15列之间变化.这是仅3列的示例:

I would like to sum the frequencies over multiple columns with pandas. The amount of columns can vary between 2-15 columns. Here is an example of just 3 columns:

code1    code2    code3
27       5        56
534      27       78
27       312      55
89       312      27

我想得到以下结果:

code    frequency
5       1
27      4
55      1
56      2
78      1
312     2
534     1

要对一列内的值进行计数不是问题,只需要一个数据帧中所有频率的总和即可显示一个值,而不管列数如何.

To count values inside one column is not the problem, just need a sum of all frequencies in a dataframe a value can appear, no matter the amount of columns.

推荐答案

您可以

You could stack and take the value_counts on the resulting series:

df.stack().value_counts().sort_index()

5      1
27     4
55     1
56     1
78     1
89     1
312    2
534    1
dtype: int64

这篇关于具有多列数据帧中的值计数的单列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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