2013-04-08 57 views
3

我试图一次删除多个列而不利用他们的字段信息。我每个月都会从县里得到一份CSV文件,而且我不想与大众分享多个领域。直到现在,每个月我都会手动删除每个字段。由于我正在尝试学习python,我想了解如何创建一个脚本来完成它。我想删除58个字段,所以我不想为每个字段写一个脚本,但希望创建一个删除它们的范围。我一直在这里搜索论坛几个小时,并尝试了很多不同的方法,我不知道从哪里开始或停止。任何帮助,将不胜感激。删除多列

+0

你有没有试过这种 [删除列 - 蟒蛇] [1] [1]:http://stackoverflow.com/questions/7588934/deleting-columns-in-a-csv-with-python – Verbatus 2013-04-08 19:45:11

+0

我确实看过。我有超过100个我想保留的字段,所以我试图不列出每个字段。除非我误解了这篇文章的所有建议,否则这是我需要做的。我愿意把它们全部列出来,但如果可能的话,宁愿避免它。 – user2259051 2013-04-08 19:55:20

回答

1

让我们假设你有一个CSV文件是这样的:

Name,Sex,Address,Age 
John,M,New York,40 
Mary,F,Los Angeles,30 

,你想保持仅列NameAddress

然后,你可以做这样的事情(Python 3中),利用该DictWriter类的extrasignore参数:

import csv 
fields = ["Name", "Address"] 

with open("test.csv") as infile, open("out.csv", "w", newline="") as outfile: 
    #   in Python 2, use open("out.csv", "wb") as outfile: 
    r = csv.DictReader(infile) 
    w = csv.DictWriter(outfile, fields, extrasaction="ignore") 
    w.writeheader() 
    for row in r: 
     w.writerow(row) 

结果:

Name,Address 
John,New York 
Mary,Los Angeles 

如果你想这样做的其他方式,我。即指定列从文件中删除,那么它是一个比较复杂:

import csv 
delete = ["Sex", "Age"] 

with open("test.csv") as infile, open("out.csv", "w", newline="") as outfile: 
    #   in Python 2, use open("out.csv", "wb") as outfile: 
    r = csv.DictReader(infile) 
    firstrow = next(r) # Need to read the first row so we know the fieldnames 
    fields = r.fieldnames 
    w = csv.DictWriter(outfile, 
         [field for field in fields if not field in delete], 
         extrasaction="ignore") 
    w.writeheader() 
    w.writerow(firstrow) 
    for row in r: 
     w.writerow(row) 
6

我很懒,所以我喜欢时,我可以使用现有的库,并已成为传道的话了pandas库。使用@Tim Pietzcker的例子:

Name,Sex,Address,Age 
John,M,New York,40 
Mary,F,Los Angeles,30 

我们可以只保留栏目,我们希望用:

import pandas as pd 
df = pd.read_csv("to_remove.csv") 
keep_cols = ["Name", "Address"] 
new_df = df[keep_cols] 
new_df.to_csv("removed.csv", index=False) 

(我们也一个行,但我认为这是像更清晰)


解释如下。首先,我们可以读取文件到称为存储对象DataFrame

>>> import pandas as pd 
>>> df = pd.read_csv("to_remove.csv") 
>>> df 
    Name Sex  Address Age 
0 John M  New York 40 
1 Mary F Los Angeles 30 

我们可以从对象选择一个或多个列:

>>> df[["Name", "Sex"]] 
    Name Sex 
0 John M 
1 Mary F 

然后写出来:

>>> new_df = df[["Name", "Sex"]] 
>>> new_df.to_csv("removed.csv", index=False) 

(该index=False位只是告诉它不要添加一个列的行数,上面的数字0,1),产生

Name,Sex 
John,M 
Mary,F 

我们也可以决定我们只希望保持柱开始以字母“A”:

>>> [col for col in df.columns if col.startswith("A")] 
['Address', 'Age'] 
>>> df[[col for col in df.columns if col.startswith("A")]] 
     Address Age 
0  New York 40 
1 Los Angeles 30 

或使用.ix方法仅从#1列保持到下至-last:

>>> df.ix[:,1:-1] 
    Sex  Address 
0 M  New York 
1 F Los Angeles 

等等。