1

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 (*)?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

10 Comments

I add alternative solution df = df.apply(lambda x: ''.join(x), axis=1)
Interesting, what is your pandas version? print (pd.show_versions())
What is type(df) ? It is DataFrame or Series ?
then use df = df.str.strip() if Series.
@ChillarAnand - Use df[['colA','colB']].apply(''.join, axis=1)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.