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.

1
  • Can you add sample data? Commented Feb 15, 2018 at 14:10

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the answer but this gives me the same result as above.
@Coder, please provide a small sample data set and your desired data set
I want my result to be like: a: 2-6, 1-2, 4-1, 0-1 (count of each value in column)
@Coder, please put a sample input and desired data sets into your question...
@MaxU perhaps it is applying value_counts over columns, if it isn't what OP wanted please reopen the question.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.