Home > other >  Add a new column in csv python
Add a new column in csv python

Time:01-27

How do I add a new column at the very beginning of csv file? I know we can do it using pandas, but I am having issue with pandas so is there another way to do it? I have something that looks like this:

a b c d
0 1 2 3

I want to do this instead:

letters a b c d
numbers 0 1 2 3

if the tables are not formatted properly here is a picture: Tables

CodePudding user response:

What do you mean by "I a am having issues" with ?
Have you tried using/running df.insert(0, "letters", "numbers") ?

Anyways, alternatively, you can use csv.reader function from module with a listcomp to insert the new column :

import csv

with open("input.csv", "r") as file:
    rows = [["letters" if idx == 0 else "numbers"]   row
            for idx, row in enumerate(csv.reader(file, delimiter=","))]

with open("output.csv", "w", newline="") as file:
    csv.writer(file, delimiter=",").writerows(rows)

Output :

from tabulate import tabulate #pip install tabulate

with open("output.csv", "r") as file:
    reader = csv.reader(file, delimiter=",")
    print(tabulate([row for row in reader]))

-------  -  -  -  -
letters  a  b  c  d
numbers  0  1  2  3
-------  -  -  -  -
  • Related