Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas concatenate alternating columns

Tags:

python

pandas

I have two dataframes as follows:

df2 = pd.DataFrame(np.random.randn(5,2),columns=['A','C'])
df3 = pd.DataFrame(np.random.randn(5,2),columns=['B','D'])

I wish to get the columns in an alternating fashion such that I get the result below:

df4 = pd.DataFrame()
for i in range(len(df2.columns)):
    df4[df2.columns[i]]=df2[df2.columns[i]]
    df4[df3.columns[i]]=df3[df3.columns[i]]

df4 

    A   B   C   D
0   1.056889    0.494769    0.588765    0.846133
1   1.536102    2.015574    -1.279769   -0.378024
2   -0.097357   -0.886320   0.713624    -1.055808
3   -0.269585   -0.512070   0.755534    0.855884
4   -2.691672   -0.597245   1.023647    0.278428

I think I'm being really inefficient with this solution. What is the more pythonic/ pandic way of doing this?

p.s. In my specific case the column names are not A,B,C,D and aren't alphabetically arranged. Just so know which two dataframes I want to combine.

like image 322
sachinruk Avatar asked Jul 26 '16 06:07

sachinruk


2 Answers

If you need something more dynamic, first zip both columns names of both DataFrames and then flat it:

df5 = pd.concat([df2, df3], axis=1)
print (df5)
          A         C         B         D
0  0.874226 -0.764478  1.022128 -1.209092
1  1.411708 -0.395135 -0.223004  0.124689
2  1.515223 -2.184020  0.316079 -0.137779
3 -0.554961 -0.149091  0.179390 -1.109159
4  0.666985  1.879810  0.406585  0.208084

#http://stackoverflow.com/a/10636583/2901002
print (list(sum(zip(df2.columns, df3.columns), ())))
['A', 'B', 'C', 'D']
print (df5[list(sum(zip(df2.columns, df3.columns), ()))])
          A         B         C         D
0  0.874226  1.022128 -0.764478 -1.209092
1  1.411708 -0.223004 -0.395135  0.124689
2  1.515223  0.316079 -2.184020 -0.137779
3 -0.554961  0.179390 -0.149091 -1.109159
4  0.666985  0.406585  1.879810  0.208084
like image 186
jezrael Avatar answered Nov 15 '22 06:11

jezrael


How about this?

df4 = pd.concat([df2, df3], axis=1)

Or do they have to be in a specific order? Anyway, you can always reorder them:

df4 = df4[['A','B','C','D']]

And without writing out the columns:

df4 = df4[[item for items in zip(df2.columns, df3.columns) for item in items]]
like image 23
kloffy Avatar answered Nov 15 '22 04:11

kloffy