Skip to content
Advertisement

Pandas unique values per row, variable number of columns with data

Consider the below dataframe:

JavaScript

Assuming my index is unique, I’m looking to retrieve the unique values per index row, to an output like the one below. I wish to keep the empty rows.

JavaScript

I have a working, albeit slow, solution, see below. The output number order is not relevant, as long all values are presented to the leftmost column and nulls to the right. I’m looking for best practices and potential ideas to speed up the code. Thank you in advance.

JavaScript

Advertisement

Answer

Another option, albeit longer:

JavaScript

If you want it to exactly match your output, you can dump it into numpy, sort and return to pandas:

JavaScript

Another option is to do the sorting within numpy before reshaping in Pandas:

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