1

I have a simple Pandas dataframe that I wish to groupby using a certain column. The df looks like the one below.

Color    Car
  R      Ford
  O      Kia
  Y      Mazda
  R      Chevrolet

I want to groupby 'Color', so the resulting df would be:

Color    Car
  R      Ford, Chevrolet 
  O      Kia
  Y      Mazda

This seems to be easy enough using pandas groupby. My code looks like the following:

df = df.groupby(['Color'])

But I get the following error:

Cannot access callable attribute 'iloc' of 'DataFrameGroupBy' objects, try using the 'apply' method 

Why does groupby not work? It seems like the most basic operation for which groupby is the perfect thing to use?

MaxB
  • 428
  • 1
  • 8
  • 24
  • 1
    Aside from your error, related: https://stackoverflow.com/questions/27298178/concatenate-strings-from-several-rows-using-pandas-groupby – EdChum Apr 04 '19 at 14:36

1 Answers1

2

Use:

df.groupby('Color')['Car'].apply(', '.join)

[out]

Color
O               Kia
R    Ford, Chevrolet
Y             Mazda
Chris Adams
  • 18,389
  • 4
  • 22
  • 39