pythonpandas

mix two dataframes with every second row


I have two dataframes that I want to mix togther first two of the second table go to the every second two of, so like this:

First table              Second table
column_1                 column_1
1                        5
2                        6
3                        7
4                        8

And then the new table will be like this:

new table
column_1
1
2
5
6
3
4
7
8

Is there easy way to do this with pandas?


Solution

  • I manage to make it like this:

    def create_order(length, phase):
        first_list = [i for i in range(length)]
        second_list = [i for i in range(length, length * 2)]
        start_i = 0
        out_list = []
        for i in range(phase, length + 1, phase):
            out_list.extend(first_list[start_i:i])
            out_list.extend(second_list[start_i:i])
            start_i = i
        return out_list
    
    df1 = pd.DataFrame({'col': [1,2,3,4]})
    df2 = pd.DataFrame({'col': [5,6,7,8]})
    order = create_order(len(df1), 2)
    out = pd.concat([df1, df2]).iloc[order]