[英]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.基本上,这种情况贯穿整个 dataframe。 I want to merge the similar columns to the dataframe below我想将类似的列合并到下面的 dataframe
Politics Arts/Culture
c c
b a
b a
a c
Use DataFrame.stack
+ DataFrame.unstack
:使用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
Try with groupby
with level=0
and axis=1
then do first
尝试使用level=0
和axis=1
的groupby
然后first
s=df.groupby(level=0,axis=1).first()
Arts/Culture Politics
0 c c
1 a b
2 a b
3 c a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.