Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: merge columns with the similar names

Politics  Politics  Politics    Arts/Culture  Arts/Culture  Arts/Culture
  nan       nan        c         nan            nan          c
  nan        b         nan        a             nan          nan
  nan        b         nan        a             nan          nan
  a          nan       nan        nan           c            nan   

Basically, this goes on throughout the dataframe. I want to merge the similar columns to the dataframe below

Politics    Arts/Culture  
 c              c
 b              a
 b              a
 a              c

like image 632
Olutomilayo Dolapo Avatar asked Mar 02 '23 06:03

Olutomilayo Dolapo


1 Answers

Use DataFrame.stack + DataFrame.unstack:

df1 = df.stack().unstack()

Result:

# print(df1)

  Arts/Culture Politics
0            c        c
1            a        b
2            a        b
3            c        a
like image 122
Shubham Sharma Avatar answered Mar 08 '23 12:03

Shubham Sharma