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
vem
  • 21
  • 3
  • print(df.to_string()) https://stackoverflow.com/questions/19124601/pretty-print-an-entire-pandas-series-dataframe – k3b Sep 17 '20 at 11:09

1 Answers1

0

use groupby and to_string

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


Animal
BIRD           YELLOW
CAT     BLACK, ORANGE
DOG             WHITE
Umar.H
  • 22,559
  • 7
  • 39
  • 74
  • 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. – vem Sep 17 '20 at 11:19
  • use `header=None` i.e `print(df.groupby('Animal')['Color'].agg(', '.join).to_string(header=None))` @vem – Umar.H Sep 17 '20 at 11:41
  • 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 – vem Sep 17 '20 at 11:50
  • 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 – Umar.H Sep 17 '20 at 12:17