Single column with value counts from multiple column dataframe

梦想的初衷 提交于 2021-02-05 06:54:04

问题


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

And I would like to have the following result:

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.


回答1:


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


来源:https://stackoverflow.com/questions/61320130/single-column-with-value-counts-from-multiple-column-dataframe

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