Skip to content
Advertisement

pandas merge columns to create new column with comma separated values

My dataframe has four columns with colors. I want to combine them into one column called “Colors” and use commas to separate the values.

For example, I’m trying to combine into a Colors column like this :

JavaScript

My code is:

JavaScript

But the output for ID 120 is:

JavaScript

And the output for ID 121 is:

JavaScript

FOUND MY PROBLEM! Earlier in my code, I replaced "None" with " " instead of NaN. Upon making the change, plus incorporating feedback to insert [x.notnull()], it works!

JavaScript

Advertisement

Answer

You just need to handle NaNs

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement