I have a table like this:
colour number letter
0 red one a
1 red two b
2 red two c
3 blue two a
4 blue two b
5 green one a
6 green two b
7 green three c
Which I made by doing:
df = pd.DataFrame([
('red', 'one', 'a'),
('red', 'two', 'b'),
('red', 'two', 'c'),
('blue', 'two', 'a'),
('blue', 'two', 'b'),
('green', 'one', 'a'),
('green', 'two', 'b'),
('green', 'three', 'c')
], columns=['colour', 'number', 'letter'])
I want to group the table by colour, and then for every remaining column get the three most common values. If there aren't three unique values for a column, then the last could be repeated or it could be NaN, either works. The output would look like:
colour red blue green
number 1 two two one
2 one two two
3 one two three
letter 1 a a a
2 b b b
3 c b c
Or:
colour red blue green
number 1 two two one
2 one NaN two
3 NaN NaN three
letter 1 a a a
2 b b b
3 c NaN c
I have already done this for a single column:
df.groupby('colour').number
.value_counts()
.groupby(level=0)
.head(3)
Output:
colour number
blue two 2
green one 1
two 1
three 1
red two 2
one 1
However I would like to do it for all columns in my dataframe and get an output like the example. I am completely stuck.