Skip to content
Advertisement

Use DataFrame column as index and append duplicates as new columns

I have a DataFrame that contains a column with dates which I’d like to use as my DataFrame’s index. The dates in that column are not necessarily unique – sometimes there might be duplicates. I wish to append duplicates as new columns. Dates that are unique can just contain NaN (or whatever) for the newly appended columns.

To clarify I’ll provide an example:

JavaScript

This will yield:

JavaScript

What I want:

JavaScript

The naming of the newly appended columns can be arbitrary. I don’t even know whether appending would be the right way to go about it. Maybe it’s easier to create a new DataFrame from scratch.

Advertisement

Answer

Use DataFrame.set_index with DataFrame.stack for unpivot data and then pivoting by GroupBy.cumcount and Series.unstack:

JavaScript

If order of output values is not important:

JavaScript

Another idea is use lambda function for reshape:

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