Skip to content
Advertisement

Python DataFrame: How to connect different columns with the same name and merge them into one column

Problem

I have a df that has many columns with the same column name. I wish to use the same column name as a key to do like UNION in SQL.

Example

see example data:

JavaScript

df:

JavaScript

df.T:

JavaScript

I need to combine the two y columns since I want to calculate how many times the words in y leads to the results to be sure. Ideally the results should be:

JavaScript

I tried many methods but they do not work. Can anybody help?

Advertisement

Answer

IIUC first melt , the using cumcount create the additional key , now you will see the problem became pivot

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