简体   繁体   English

将列名添加到 csv 文件,python

[英]Adding column names to csv file, python

I have an csv file that looks like this:我有一个看起来像这样的 csv 文件:

"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".在第一列中,我想添加 name = "name" 和第二列 = "id"。 I want to do this because I want to be able to select in python the whole first or second column我想这样做是因为我希望能够在 python 中选择整个第一列或第二列

So, if you store this csv file in says test.csv , there is an easy way to do it using pandas library as follows因此,如果您将此csv文件存储在test.csv ,则有一种使用pandas库的简单方法,如下所示

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'.如果 CSV 文件不在您编写代码的同一位置,则您需要提及总数据路径而不是“文件名.csv”。 To get the exact path of the file, use "shift+right click of the mouse" on the file.要获得文件的确切路径,请在文件上使用“shift+鼠标右键单击”。 You will find the option "Copy as path".您将找到“复制为路径”选项。 Copy and paste it in the place of "file name.csv".将其复制并粘贴到“文件名.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.如果在读取文件时不使用“header=None”,则第一行中的数据将作为标题。 Now if you change the column names, you will lose the data in the first row of your original file.现在,如果您更改列名,您将丢失原始文件第一行中的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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