0

How can I get unique values with count of each value for each column in a pandas dataframe using for loop:

Following code gives me count of each unique value for each column but I want the values as well.

import pprint

col_uni_val={}
for i in data.columns:
    col_uni_val[i] = len(data[i].unique())

pprint.pprint(col_uni_val)

For example:

A  B
1  4
1  4
2  6
2  6
2  6
3  6

I want my output as :

A:
1 - 2
2 - 3
3 - 1

B:
4 - 2
6 - 4

Also since my number of columns is huge can i do this using indexed loop.

Coder
  • 15
  • 1
  • 9

1 Answers1

2

Demo:

In [351]: d
Out[351]:
   A  B
0  1  4
1  1  4
2  2  6
3  2  6
4  2  6
5  3  6

In [352]: res = {col:d[col].value_counts() for col in d.columns}

In [353]: res['A']
Out[353]:
2    3
1    2
3    1
Name: A, dtype: int64

In [354]: res['B']
Out[354]:
6    4
4    2
Name: B, dtype: int64
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419