Home > OS >  Merge content of two csv files in alternate rows
Merge content of two csv files in alternate rows

Time:11-07

I have two CSV files
csv1:

header
a
b
c

csv2:\

header
e
f
g

I want to merge these two files to another CSV in alternate rows like
output.csv:

header
a
e
b
f
c
g

Can this be done? Thanks in advance

CodePudding user response:

Not sure if this is the fastest way but it works

import pandas as pd
from itertools import chain, zip_longest

x = pd.DataFrame()
x["header"] = [1, 3, 5, 7]

y = pd.DataFrame()
y["header"] = [2, 4, 6, 8, 10, 21]

chained = list(chain.from_iterable(zip_longest(x["header"].to_list(), y["header"].to_list())))
df = pd.DataFrame()
df["header"] = chained
df = df.dropna()

CodePudding user response:

Assuming csv 1 read into df1

Assuming csv 2 read into 'df2`

df1.T.join(df2.T, rsuffix='r').T.reset_index(drop=True)
  • Related