简体   繁体   中英

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?

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}

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