Home > Back-end >  How can I add a column of "ID" to an already created csv but without the actual "ID&q
How can I add a column of "ID" to an already created csv but without the actual "ID&q

Time:05-27

Say I have:

john,32,male
josh,10,male
sylvia,92,female

I need to edit it for some database manipulation later on and have a unique ID for each (preferably in order), such as:

0,john,32,male
1,josh,10,male
2,sylvia,92,female

I'm seeing solutions online but a lot of them include headers and even trying to edit them, it ends up causing issues.

CodePudding user response:

Using Python Pandas:

import pandas as pd

pd.read_csv('file.csv', header = None).to_csv('file2.csv', header = False)

Explanation

Read CSV file without header into a dataframe

df = pd.read_csv('file.csv', header = None)

Write Dataframe to CSV file with index but no header

df.to_csv('file2.csv', header = False)

Piping these two commands together we have the above one-liner

CodePudding user response:

with open('file.csv', 'r ') as f:
    data = [f'{i},{x}' for i, x in enumerate(f.readlines())]
    f.seek(0)
    f.writelines(data)
  • Related