Home > Back-end >  Combine 2 columns end to end pandas
Combine 2 columns end to end pandas

Time:01-27

I'm trying to combine 2 columns end to end from the same data frame into a new data frame. My columns are

a a1 b b1

1 2 3 4

5 6 7 8

My expected output:

a b

1 3

5 7

2 4

6 8

I tried

import pandas as pd
d1 = [d["a"], d['b']]
d2 = [d["a1"], d['b2']]

d3= pd.DataFrame({"a":[],"b":[]})
d3=pd.concat(d1, axis=1, ignore_index=True)
d3=pd.concat(d2, axis=1, ignore_index=True)

I'm only getting series objects as a result.

Note: Sorry if anything is confusing, I'm new in the coding Thank you!

CodePudding user response:

Try the below sample code if it helps.

  df=pd.DataFrame({'a':[1,5],
                    'a1':[2,6],
                    'b':[3,7],
                    'b1':[4,8]})


 df0=df.loc[:,('a','b')]
 df1=df.loc[:,('a1','b1')]
 df1.columns=['a','b']
 pd.concat([df0,df1],axis=0).reset_index(drop=True)

enter image description here

CodePudding user response:

Sure the below can be simplified further, but this works for now.

#import pandas
import pandas as pd

#recreate dataframe
df = pd.DataFrame({'a':[1,5],
                  'a1':[2,6],
                  'b':[3,7],
                  'b1':[4,8]})

#create expected columns
a = df['a'].append(df['a1'], ignore_index=True)
b = df['b'].append(df['b1'], ignore_index=True)

#concatenate on columns and rename columns
df2 = pd.concat([a,b], axis = 1)
df2.columns = ['a','b']
df2
  •  Tags:  
  • Related