[英]How to merge pandas columns within the same dataframe?
I have the following pandas dataframe:我有以下熊猫数据框:
colA ColB ColC
0 D
1 G
2 A
3 B
4 C
How can I merge it into (*):如何将其合并为 (*):
colA
0 D
1 G
2 A
3 B
4 C
So far I tried to:到目前为止,我试图:
df = pd.DataFrame.merge([df.ColA, df.ColB, df.ColC], how='right')
df
However, it doesn't worked.但是,它不起作用。 How can I get (*)?我怎样才能得到 (*)?
You can use DataFrame.sum
:您可以使用DataFrame.sum
:
df = df.sum(axis=1)
If NaN
values you can fillna
first:如果NaN
值,您可以先fillna
:
df = df.fillna('').sum(axis=1)
print (df)
0 D
1 G
2 A
3 B
4 C
dtype: object
Another solution with apply
- join
:使用apply
- join
另一种解决方案:
df = df.apply(''.join, axis=1)
#df = df.apply(lambda x: ''.join(x), axis=1)
print (df)
0 D
1 G
2 A
3 B
4 C
dtype: object
Solution with Series.combine_first
, but need NaN
values: Series.combine_first
解决方案,但需要NaN
值:
print (df)
colA ColB ColC
0 NaN D NaN
1 NaN NaN G
2 A NaN NaN
3 NaN B NaN
4 C NaN NaN
df = df.colA.combine_first(df.ColB).combine_first(df.ColC)
print (df)
0 D
1 G
2 A
3 B
4 C
Name: colA, dtype: object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.