简体   繁体   中英

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 :

df = df.sum(axis=1)

If NaN values you can fillna first:

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 :

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM