piRSquared piRSquared - 1 year ago 60
Python Question

Interweave two dataframes

Suppose I have two dataframes

d1
and
d2


d1 = pd.DataFrame(np.ones((3, 3), dtype=int), list('abc'), [0, 1, 2])
d2 = pd.DataFrame(np.zeros((3, 2), dtype=int), list('abc'), [3, 4])





d1

0 1 2
a 1 1 1
b 1 1 1
c 1 1 1





d2

3 4
a 0 0
b 0 0
c 0 0





What is an easy and generalized way to interweave two dataframes' columns. We can assume that the number of columns in
d2
is always one less than the number of columns in
d1
. And, the indices are the same.

I want this:

pd.concat([d1[0], d2[3], d1[1], d2[4], d1[2]], axis=1)

0 3 1 4 2
a 1 0 1 0 1
b 1 0 1 0 1
c 1 0 1 0 1

Answer Source

Using pd.concat to combine the DataFrames, and toolz.interleave reorder the columns:

from toolz import interleave

pd.concat([d1, d2], axis=1)[list(interleave([d1, d2]))]

The resulting output is as expected:

   0  3  1  4  2
a  1  0  1  0  1
b  1  0  1  0  1
c  1  0  1  0  1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download