使用 python 解析和操作 csv

csv parsing and manipulation using python

我有一个 csv 文件,我需要使用 python 进行解析。

triggerid,timestamp,hw0,hw1,hw2,hw3
1,234,343,434,78,56
2,454,22,90,44,76

我需要逐行读取文件,从中切出 triggerid、timestamp 和 hw3 列。但是列序列可能会从 运行 运行 改变。所以我需要匹配字段名称,计算列数,然后将输出文件打印为:

triggerid,timestamp,hw3
1,234,56
2,454,76

另外,有没有一种方法可以生成散列-table(就像我们在 perl 中那样),这样我就可以存储 hw0 的整个列(hw0 作为键,列中的值作为值) 进行其他修改。

既然你已经有了切片的解决方案,这里有一些问题的散列 table 部分:

import csv
with open('/path/to/file.csv','rb') as fin:
    ht = {}
    cr = csv.reader(fin)
    k = cr.next()[2]
    ht[k] = list()
    for line in cr:
        ht[k].append(line[2])

我不确定你说的 "count the column" 是什么意思。

读取数据的一种简单方法是使用 pandas,它专为此类操作而设计。这将使用第一行作为标题从您的数据创建一个 pandas DataFrame。

In [374]: import pandas as pd
In [375]: d = pd.read_csv("30735293.csv")

In [376]: d
Out[376]:
   triggerid  timestamp  hw0  hw1  hw2  hw3
0          1        234  343  434   78   56
1          2        454   22   90   44   76

您可以select其中一列使用单个列名称,多个列使用名称列表:

In [377]: d[["triggerid", "timestamp", "hw3"]]
Out[377]:
   triggerid  timestamp  hw3
0          1        234   56
1          2        454   76

您还可以调整索引,使一个或多个数据列用作索引值:

In [378]: d1 = d.set_index("hw0"); d1
Out[378]:
     triggerid  timestamp  hw1  hw2  hw3
hw0
343          1        234  434   78   56
22           2        454   90   44   76

使用 .loc 属性,您可以检索任何索引行的系列:

In [390]: d1.loc[343]
Out[390]:
triggerid      1
timestamp    234
hw1          434
hw2           78
hw3           56
Name: 343, dtype: int64

您可以使用列名从 one-row 系列中检索各个列值:

In [393]: d1.loc[343]["triggerid"]
Out[393]: 1

我使用了不同的方法(using.index 函数)

bpt_mode = ["bpt_mode_64","bpt_mode_128"] 
with open('StripValues.csv') as file: 
for _ in xrange(1): 
next(file)
 for line in file:
 stat_values = line.split(",") 
draw_id=stats.index('trigger_id')
 print stat_values[stats.index('trigger_id')],',',
 for j in range(len(bpt_mode)): 
print stat_values[stats.index('hw.gpu.s0.ss0.dg.'+bpt_mode[j])],',', file.close()

@holdenweb 尽管我不知道如何将输出打印到文件中。目前我正在重定向 运行 脚本 你能提供一个写入文件的解决方案吗?将对单个文件进行多次写入。