pinq-
pinq-

Reputation: 391

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?

Upvotes: 0

Views: 56

Answers (2)

pinq-
pinq-

Reputation: 391

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]

Upvotes: 0

mozway
mozway

Reputation: 262194

Craft an indexer with numpy.argsort, concat, reorder:

df1 = pd.DataFrame({'col': [1,2,3,4]})
df2 = pd.DataFrame({'col': [5,6,7,8]})

order = np.argsort(
  np.r_[np.arange(len(df1))//2,
        np.arange(len(df2))//2
       ]
)

out = pd.concat([df1, df2]).iloc[order]

Output:

   col
0    1
1    2
0    5
1    6
2    3
3    4
2    7
3    8

You can generalize to other steps:

N = 3
order = np.argsort(
  np.r_[np.arange(len(df1))//N,
        np.arange(len(df2))//N
      ]
    )

Output:

   col
0    1
1    2
2    3
0    5
1    6
2    7
3    4
3    8

Upvotes: 0

Related Questions