0

I have a Pandas DF as below, and I'm struggling with printing it in a good looking format... Could someone please show me how to combine those two values from same column values?

data = {'Animal':['DOG','CAT','CAT','BIRD'],
        'Color':['WHITE','BLACK','ORANGE','YELLOW']}
df = pd.DataFrame(data)
df

And I wish the print result would be exactly as below:

DOG, WHITE
CAT, BLACK, ORANGE
BIRD, YELLOW
1

1 Answer 1

0

use groupby and to_string

print(df.groupby('Animal')['Color'].agg(', '.join).to_string())


Animal
BIRD           YELLOW
CAT     BLACK, ORANGE
DOG             WHITE
Sign up to request clarification or add additional context in comments.

4 Comments

Hi, thank you so much for replying. The way you did combines the two values with same index. But the result will still show the "Animal" column, I only want the rows' values, and between the Animal and Color columns, only add ", ". Like the way I show in my question.
use header=None i.e print(df.groupby('Animal')['Color'].agg(', '.join).to_string(header=None)) @vem
But after the print function, there is still so many blank spaces between "Animal" and "Color". I actually want to combine them with one comma and one space. i.e. CAT, BLACK, ORANGE @Manakin
try print(df.groupby('Animal')['Color'].agg(','.join).reset_index().agg(','.join,1).to_string(header=None,index=None)) you need to agg all your columns into a single field then print, won't be very performant though. @vem

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.