Pandas:合并具有相似名称的列

Posted

技术标签:

【中文标题】Pandas:合并具有相似名称的列【英文标题】:Pandas: merge columns with the similar names 【发布时间】:2020-10-25 18:18:13 【问题描述】:
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   

基本上,这会贯穿整个数据帧。 我想将相似的列合并到下面的数据框

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

【问题讨论】:

列名实际上是相似的还是相同的?我知道默认情况下,熊猫会在导入时重命名此类列,除非您手动或通过某些函数声明了列。 他们是一样的 【参考方案1】:

使用DataFrame.stack + DataFrame.unstack:

df1 = df.stack().unstack()

结果:

# print(df1)

  Arts/Culture Politics
0            c        c
1            a        b
2            a        b
3            c        a

【讨论】:

【参考方案2】:

尝试使用groupbylevel=0axis=1 然后使用first

s=df.groupby(level=0,axis=1).first()
  Arts/Culture Politics
0            c        c
1            a        b
2            a        b
3            c        a

【讨论】:

以上是关于Pandas:合并具有相似名称的列的主要内容,如果未能解决你的问题,请参考以下文章