使用Python删除列CSV文件

时间:2017-10-04 11:55:36

标签: python csv

我正在尝试使用python删除csv文件中的多个列,但我的代码只删除了第一行的列...任何解决方案?

这是我在Python 3.5中的代码:

import csv
with open("source.csv","r") as source:
    rdr= csv.reader( source )
    with open("result.csv","w") as result:
        wtr= csv.writer( result )
        for r in rdr:
            wtr.writerow( (r[0], r[1], r[3], r[4]) )

在运行python脚本之前我的csv文件:

1 row - Policy Name,Client Name,Job Duration,Protected,Schedule/Level Type,Job Start Time,Job End Time,Job Directory,Job Status

2 row -
 PRD19_CABFLAFPRD01_9999CA2,cabflafprd01,15:11:32,"11,161,482.25",Full,"Sep 4, 2017 7:31:09 AM","Sep 4, 2017 10:42:41 PM",/cabflafprdp/grupos,Successful,,,,,,,,

3 row - PRD19_CABFLAFPRD01_9999CA0,cabflafprd01,09:26:50,"4,673,460.75",Full,"Sep 4, 2017 7:31:09 AM","Sep 4, 2017 4:57:59 PM",/cabflafprdp/homedir,Successful,,,,,,,,

后:

1 - Policy Name,Client Name,Protected,Schedule/Level Type

2 - PRD19_CABFLAFPRD01_9999CA0,cabflafprd01,08:29:51,0,Full,"Jun 1, 2017 4:30:16 AM","Jun 1, 2017 1:00:07 PM",/cabflafprdp/homedir,Successful,,,

3 - PRD19_CABFLAFPRD01_9999CA0,cabflafprd01,08:28:07,"4,723,908",Full,"Jun 1, 2017 4:32:00 AM","Jun 1, 2017 1:00:07 PM",/cabflafprdp/homedir,Successful,,,

1 个答案:

答案 0 :(得分:0)

当您使用names =" abcde"创建数据框名称时,Pandas是每行的绝佳选择。然后每列将有一个字母,然后是下一个命令

import pandas as pd

df1 = pd.read_csv('source', names = 'abc', header = 0)
df2 = df1.drop('b', axis = 1)

print (df2)

然后将文件输出回csv

df3 = data.to_csv('source_with_dropped_columns')

第二行代码将删除名为" b"

的列