Skip to content
Advertisement

Python/Pandas: If Column has multiple values, convert to single row with multiples values in list

In my DataFrame, I have many instances of same AutoNumber having different KeyValue_String. I would like to convert these instances to a single row where the KeyValue_String is a list comprised of the multiple unique values.

JavaScript

The desired output would look like this, except I want to keep all of the other columns

JavaScript

Advertisement

Answer

If I understand correctly, you could opt for using groupby, transform, and unique.

JavaScript

Then you can drop duplicates assuming as mentioned in the comments that rows with the same AutoNumber contain duplicate information besides the KeyValue_String.

JavaScript

I would advise if you want arrays you keep everything in the column as an array, and don’t expend effort putting mixed types in the column which will just be harder to work with anyways.

Demo

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