Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Data Science by (50.2k points)

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

1 Answer

0 votes
by (107k points)

Just use the pd.concat to consolidate 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

Refer to the following links for more information regarding the same:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html

https://toolz.readthedocs.io/en/latest/api.html#toolz.itertoolz.interleave

If you are interested in learning Pandas and want to become an expert in Python Programming, then check out this Python Course and upskill yourself.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...