Pandas merge alternating columns

I have two data frames:

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

I want to get the columns in an alternating way to get the following result:

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 really ineffective with this solution. What is the greater pythonic / pandic way to do this?

ps In my particular case, the column names are not A, B, C, D and are not in alphabetical order. Just know which two data frames I want to combine.

+4
source share
4 answers

If you need something more dynamic, first write down both column names of both DataFrames, and then set 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
+7
source

How about this?

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

Or should they be in a certain order? In any case, you can always change their order:

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

:

df4 = df4[[item for items in zip(df2.columns, df3.columns) for item in items]]
+2

concat, reindex_axis.

df = pd.concat([df2, df3], axis=1)
df.reindex_axis(df.columns[::2].tolist() + df.columns[1::2].tolist(), axis=1)
+2

Add even indexes to columns df2and odd indexes to columns df3. Use these new levels to sort.

df2_ = df2.T.set_index(np.arange(len(df2.columns)) * 2, append=True).T
df3_ = df3.T.set_index(np.arange(len(df3.columns)) * 2 + 1, append=True).T

df = pd.concat([df2_, df3_], axis=1).sort_index(1, 1)
df.columns = df.columns.droplevel(1)

df

enter image description here

+1
source

Source: https://habr.com/ru/post/1649114/


All Articles