Merge content of two csv files in alternate rows

Question:

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

Asked By: Joz

||

Answers:

Will definitly not be 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()
Answered By: Achille G

Assuming csv 1 read into df1

Assuming csv 2 read into df2

df1 = pd.DataFrame({'header': ['a', 'b', 'c']})
df2 = pd.DataFrame({'header': ['d', 'e', 'f']})

print(pd.concat(
    [df1, df2], axis=1
).stack().reset_index(1, drop=True))

output #

0    a
0    d
1    b
1    e
2    c
2    f
Answered By: Bhargav

A more "traditional" Python approach that doesn’t require any external dependencies.

with open("csv1.txt") as f1, open("csv2.txt") as f2, open("output.txt", "w") as fo:
    csv1, csv2 = f1.readlines(), f2.readlines()
    header, _ = csv1.pop(0), csv2.pop(0)
    output = [header]
    for i in range(min(len(csv1),len(csv2))):
        output.extend([csv1[i], csv2[i]])
    fo.writelines(output)
Answered By: fbattello
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.