简体   繁体   中英

Adding column names to csv file, python

I have an csv file that looks like this:

"FROST, CARMILLA","AA2 35"
"KILLRAVEN/JONATHAN R","AA2 35"
"M'SHULLA","AA2 35"
"24-HOUR MAN/EMMANUEL","AA2 35"
"OLD SKULL","AA2 35"
"G'RATH","AA2 35"
"3-D MAN/CHARLES CHAN","M/PRM 35"
"3-D MAN/CHARLES CHAN","M/PRM 36"
"3-D MAN/CHARLES CHAN","M/PRM 37"

......

To the first column I want to add name = "name" and the second one = "id". I want to do this because I want to be able to select in python the whole first or second column

So, if you store this csv file in says test.csv , there is an easy way to do it using pandas library as follows

import pandas as pd
df = pd.read_csv('test.csv', header=None)
df.rename(columns={0: 'name', 1: 'id'}, inplace=True)
df.to_csv('test_with_col.csv', index=False) # save to new csv file
import pandas as pd

df = pd.read_csv('file name.csv', header=None)
df.columns = ['name1' 'name2' 'name3'] 
  1. If the CSV file is not in the same location where you are writing the code, then you need to mention the total data path in place of 'file name.csv'. To get the exact path of the file, use "shift+right click of the mouse" on the file. You will find the option "Copy as path". Copy and paste it in the place of "file name.csv".

  2. If the file does not open, try using "\\"(double backslash) in place of "\\"(single backslash) in the file path.

  3. If you do not use "header=None" while reading the file, the data in the first row will be taken as a header. Now if you change the column names, you will lose the data in the first row of your original file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM