Search code examples
pandasconcatenation

Interweave rows from 2 dfs panda


I have 2 dfs, I want to interweave the rows from these 2 dfs to build 1 df.

import pandas as pd
df1 = pd.DataFrame({'SONY': [1,3,5,7,9],}, index=['a','b','c','d','e'])
df1 = pd.DataFrame({'SONY': [2,4,6,8,10],}, index=['a','b','c','d','e'])

Expected output

   SONY
a   1
a   2
b   3
b   4
c   5
c   6
d   7
d   8
e   9
e   10

My failed attempt, I was thinking of looping over the dfs and extracting the rows and putting them in a list and then building a df from it.

dfs=[]
numofrows = len(df.index)
for x in range(0, numofrows):
    dfs.append(pd.concat([df1.iloc[x], df2.iloc[x]], ignore_index=True))

Why am I doing this: I'm trying to replicate a df behind a chart and this is what it looks like.


Solution

  • You should make it so the indexes are not the same, then use zip, numpy.hstack, pandas.concat and DataFrame.reindex:

    import numpy as np
    
    # Change indices
    df1.index+='1'
    df2.index+='2'
    
    order = np.hstack(list(zip(df1.index, df2.index)))
    df = pd.concat([df1, df2]).reindex(order)
    print(df)
    

    [out]

        SONY
    a1     1
    a2     2
    b1     3
    b2     4
    c1     5
    c2     6
    d1     7
    d2     8
    e1     9
    e2    10