Issue
data = {'Col1': [1, 2, 2, 3, 1],
'Col2': ['A', 'B', 'B', 'A', 'C']}
df = pd.DataFrame(data)
i want to get a dictionary like:
{'Col1': {1:2, 2:2, 3:1},
'Col2': {'A':2, 'B':2, 'C':1}
without using any kind of loop
, apply
or agg
method.
I have tried something like this:
count_matrix = df.stack().groupby(level=1).value_counts()
count_matrix = count_matrix.unstack(0)
count_matrix = count_matrix.to_dict()
but it does not work, because it inserts nan
value to fill blanks when unstacking.
Solution
If you want to use pure pandas without explicit loops, you can go with agg
, value_counts
and to_dict
:
df.agg(lambda x: x.value_counts().to_dict()).to_dict()
Or, overriding the loop limitation with map
:
dict(map(lambda x: (x[0], x[1].value_counts().to_dict()), df.items()))
Output:
{'Col1': {1: 2, 2: 2, 3: 1}, 'Col2': {'A': 2, 'B': 2, 'C': 1}}
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.