简体   繁体   English

Python熊猫统计每列中的出现次数

[英]Python pandas count occurrences in each column

I am new to pandas. 我是熊猫新手。 Can someone help me in calculating frequencies of values for each columns. 有人可以帮助我计算每一列的值频率吗?

Dataframe: 数据帧:

id|flag1|flag2|flag3|  
---------------------
1 |  1  |   2 |   1 |  
2 |  3  |   1 |   1 |  
3 |  3  |   4 |   4 |  
4 |  4  |   1 |   4 |  
5 |  2  |   3 |   2 |  

I want something like 我想要类似的东西

id|flag1|flag2|flag3|  
---------------------
1 |  1  |   2 |   2 |  
2 |  1  |   1 |   1 |  
3 |  2  |   1 |   0 |  
4 |  1  |   1 |   2 |  

Explanation - id 1 has 1 value in flag1, 2 values in flag2 and 2 values in flag3. 说明-id 1在flag1中具有1个值,在flag2中具有2个值,在flag3中具有2个值。

First filter only flag columns by filter or removing id column and then apply function value_counts , last replace NaN s to 0 and cast to int s: 首先通过filter或删除id列仅过滤flag列,然后apply函数value_counts ,最后将NaN替换为0并强制转换为int

df = df.filter(like='flag').apply(lambda x: x.value_counts()).fillna(0).astype(int)
print (df)
   flag1  flag2  flag3
1      1      2      2
2      1      1      1
3      2      1      0
4      1      1      2

Or: 要么:

df = df.drop('id', 1).apply(lambda x: x.value_counts()).fillna(0).astype(int)
print (df)
   flag1  flag2  flag3
1      1      2      2
2      1      1      1
3      2      1      0
4      1      1      2

Thank you, Bharath for suggestion: 谢谢巴拉斯的建议:

df = df.filter(like='flag').apply(pd.Series.value_counts()).fillna(0).astype(int)

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

相关问题 熊猫计算列中每个值的出现次数 - Pandas count the occurrences of each value in column Pandas DataFrame 在列中每次出现后计算每个元素的出现次数 - Pandas DataFrame count occurrences for each element after each appearance in column pandas:计算列表中每个元素在列表列中唯一出现的次数 - pandas: count the number of unique occurrences of each element of list in a column of lists 熊猫,Python:每5分钟计算一次唯一的名称方法出现次数 - Pandas, python: Count unique name-method occurrences each 5 minutes 熊猫:增量计算列中的出现次数 - Pandas: Incrementally count occurrences in a column Pandas 的值计数字符串出现在 Python 中的列表类型的列 - Value Count String Occurrences for Pandas Column of Lists type in Python 如何计算 Python Pandas 中逗号分隔列的出现次数 - How to count the number of occurrences on comma delimited column in Python Pandas 如何使用Python计算Pandas列中指定值的出现 - How to count occurrences of specified value in column in Pandas using Python 在熊猫python中按列计算匹配部分字符串的出现次数 - count occurrences matching partial string by column in pandas python Python 计数 pandas 在 pandas 中 substring 的出现次数 - Python Count occurrences of a substring in pandas by row appending distinct string as column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM