Panda's row count question

Asked 2 years ago, Updated 2 years ago, 43 views

When there is an Excel like in the picture, I want to know how many times the name came out for each note (e.g. 2 times for a and 1 time for b in note A). We know that there is a function called value_counts, but this function changes the order (by itself b shuffles the order to 1 and a to 2), and it should not change the order. Is there a way to know how many times the names came out for each note so that the order doesn't change?

pandas

2022-09-21 10:06

1 Answers

(Self-contained b mixed order 1 and a mixed order 2) I don't understand what this means.
It's easy to understand if you write down the results you want.
I just applied value_counts for each remark.

import pandas as pd
df = pd.DataFrame({'col1': ['A']*3 + ['D']*2 + ['C']*2 + ['B']*3,
                   'col2': ['a', 'b', 'a', 'c', 'a', 'a', 'a', 'b', 'c', 'd']})
print(df.groupby('col1').apply(lambda x: x['col2'].value_counts()))


2022-09-21 10:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.