0

I have a pandas dataframe, and whenever the classification column is 1, I want to add the string "black" to it. This is what my dataframe is right now:

   Explanation                              Classification:
 blue, red, pink                                   1
  green, red                                       0
 yellow, purple                                    0
      red                                          1

and this is what I want:

   Explanation                              Classification:
 blue, red, pink, black                            1
  green, red                                       0
 yellow, purple                                    0
      red, black                                   1

please help!

ehkhacha
  • 21
  • 1
  • 3

1 Answers1

0

This should do:

df.loc[df.Classification == 1, "Explanation"] += ", black"

NB: Depending on your application, it might be a good idea to split the color column into separate columns for each color (e.g. if you ever need to count colors).

fsimonjetz
  • 5,644
  • 3
  • 5
  • 21
  • I don't know why that didn't work :/ – ehkhacha Aug 30 '22 at 23:52
  • What exactly didn't work? Maybe share some sample data (see [How to make good reproducible pandas examples](https://stackoverflow.com/a/20159305/15873043)). Are the column names correct? – fsimonjetz Aug 31 '22 at 07:46
  • I didn't realize that 1 in my dataframe was cast as a str instead of an int like it was in this example. it works now, thank you! – ehkhacha Aug 31 '22 at 16:57