3

I have a dataset like this.

A  B  C  A2
1  2  3   4
5  6  7   8

and I want to combine A and A2.

A  B  C
1  2  3
5  6  7
4 
8 

how can I combine two columns? Hope for help. Thank you.

1
  • 1
    Does this work? df.A = (df.A).append(df.A2) . If it works, it might fill the other cells on the neighbouring columns with NaN or zeroes, I am not sure. Commented Mar 30, 2021 at 8:46

3 Answers 3

3

I don't think it is possible directly. But you can do it with a few lines of code:

df = pd.DataFrame({'A':[1,5],'B':[2,6],'C':[3,7],'A2':[4,8]})

df_A2 = df[['A2']]
df_A2.columns = ['A']
df = pd.concat([df.drop(['A2'],axis=1),df_A2])

You will get this if you print df:

   A    B    C
0  1  2.0  3.0
1  5  6.0  7.0
0  4  NaN  NaN
1  8  NaN  NaN
Sign up to request clarification or add additional context in comments.

Comments

3

You could append the last columns after renaming it:

df.append(df[['A2']].set_axis(['A'], axis=1)).drop(columns='A2')

it gives as expected:

   A    B    C
0  1  2.0  3.0
1  5  6.0  7.0
0  4  NaN  NaN
1  8  NaN  NaN

Comments

1

if the index is not important to you:

import pandas as pd

pd.concat([df[['A','B','C']], df[['A2']].rename(columns={'A2': 'A'})]).reset_index(drop=True)

Comments

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.