Home > Blockchain >  How do I copy columns from one CSV file to another CSV file?
How do I copy columns from one CSV file to another CSV file?

Time:11-26

I have an input.csv file, and I want to copy only those lines in which calling phone is 92 to the output.csv file.

this is what input.csv looks like

calling phone;receiving phone;date;price
49;45;2020-11-08;12
65;39;2020-06-21;8
40;35;2020-01-10;4
28;56;2020-07-19;10
46;68;2020-08-22;14
65;92;2020-05-28;1
11;12;2020-07-11;11
70;76;2020-02-16;15
92;88;2020-04-24;0
92;84;2021-01-19;19
45;76;2020-03-17;11
78;67;2020-08-11;2

CodePudding user response:

You can simply do that by

import pandas as pd

df = pd.read_csv("input.csv", delimiter=";")

output = df.where(df["calling phone"] == 92).dropna()

output.to_csv("output.csv", sep=";")

What the code does is that it uses pandas to import the .csv file, filter the file for rows that match the number you which to find and export it to another .csv file.

You could also achieve the same goal with regex directly, but I guess that would complicate the matter a little. Hope that helped.

CodePudding user response:

You can do this with pure Python like this:

import csv


out = []
with open("input.csv", newline="") as csvfile:
    reader = csv.reader(csvfile, delimiter=";")
    # Get the header.
    out.append(next(reader))
    for row in reader:
        if row[0] == "92":
            out.append(row)


with open("out.csv", "w", newline="") as csvfile:
    writer = csv.writer(csvfile, delimiter=";")
    writer.writerows(out)

Here's out.csv after running that script:

calling phone;receiving phone;date;price
92;88;2020-04-24;0
92;84;2021-01-19;19
  • Related