简体   繁体   中英

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.

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM