Austin
Austin

Reputation: 7329

Pandas DataFrame value_counts dict of dicts

I'm trying to create a dictionary where the keys are pandas columns (all type object), and the keys are dictionaries with the value_counts() for each respective column.

I tried to do it this way, but I'm getting TypeError: unhashable type: 'dict':

value_counts_dict = {(c, dict(df[c].value_counts())) for c in df}

This alternative works, but it gives me a list of tuples instead:

value_counts_tuples = [(c, dict(df[c].value_counts())) for c in df]

If this is possible would someone please show me how?

Upvotes: 2

Views: 1484

Answers (1)

jezrael
jezrael

Reputation: 862751

I believe you need:

value_counts_dict = {c: df[c].value_counts().to_dict() for c in df}

Or:

value_counts_dict = {c: dict(df[c].value_counts()) for c in df}

Upvotes: 3

Related Questions