删除多个列

时间:2013-04-08 19:33:27

标签: csv multiple-columns

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

2 个答案:

答案 0 :(得分: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中的列保留为倒数第二个:

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

等等。

答案 1 :(得分:1)

假设您有一个这样的CSV文件:

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

并且您希望仅保持NameAddress

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

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)