Python:如何打印特定列,并在读取csv的列之一上剪切一些字符串

时间:2017-01-12 10:17:39

标签: python-2.7

是Python的新手,因此为基本问题道歉。

我有一个下面提到的格式的csv文件。

##cat temp.csv
Id,Info,TimeStamp,Version,Numitems,speed,Path
18699504331,NA/NA/NA,2017:01:01:13:40:31,3.16,6,781.2kHz,/home/user1
31287345804,NA/NA/NA,2017:01:03:14:35:04,3.16,2,111.5MHz,/home/user2
16360534162,NA/NA/NA,2017:01:02:21:39:51,3.16,3,230MHz,/home/user3

我想阅读csv并仅打印感兴趣的特定列,并以可读的方式在其中一列中剪切一些字符串,以便我可以使用它。

这是python代码:

cat temp.py

import csv                   

with open('temp.csv') as cvsfile:
readcsv = csv.reader(cvsfile, delimiter=',')
   Id =[]                                      
   Info =[]                                    
   Timestamp =[]                               
   Version =[]
   Numitems =[]
   Speed =[]
   Path =[]

for row in readcsv:
   lsfid = row[0]
   modelinfo = row[1]
   timestamp = row[2]
   compilever = row[3]
   numofavb = row[4]
   frequency = row[5]
   designpath = row[6]

   Id.append(lsfid)
   Info.append(modelinfo)
   Timestamp.append(timestamp)
   Version.append(compilever)
   Numitems.append(numofavb)
   Speed.append(frequency)
   Path.append(designpath)

   print(Id)
   print(Info)
   print(Timestamp)
   print(Version)
   print(Numitems)
   print(Speed)
   print(Path)

输出:

python temp.py
['Id', '18699504331', '31287345804', '16360534162', '18772620814', '18699504331', '31287345804', '16360534162']
['Info', 'NA/NA/NA', 'NA/NA/NA', 'NA/NA/NA', 'NA/NA/NA', 'NA/NA/NA', 'NA/NA/NA', 'NA/NA/NA']
['TimeStamp', '2017:01:01:13:40:31', '2017:01:03:14:35:04', '2017:01:02:21:39:51', '2017:01:03:14:40:47', '2017:01:01:13:40:31', '2017:01:03:14:35:04', '2017:01:02:21:39:51']
['Version', '3.16', '3.16', '3.16', '3.16', '3.16', '3.16', '3.16']
['Numitems', '6', '2', '3', '2', '6', '2', '3']
['speed', '781.2kHz', '111.5MHz', '230MHz', '100MHz', '781.2kHz', '111.5MHz', '230MHz']
['Path', '/home/user1', '/home/user2', '/home/user3', '/home/user4', '/home/user5', '/home/user6', '/home/user7']

但我想要的是组织良好的外观,我选择要打印的列,如下所示......

Id      Info        TimeStamp       Version     Numitems    speed       Path

18699504331 NA/NA/NA    2017:01:01:13:40:31 3.16        6       781.2kHz    user1
31287345804 NA/NA/NA    2017:01:02:21:39:51 3.16        2       111.5MHz    user2
31287345804 NA/NA/NA    2017:01:02:21:39:51 3.16        2       111.5MHz    user3

非常感谢任何帮助!

先谢谢 Velu.V

1 个答案:

答案 0 :(得分:0)

查看numpy的genfromtxt功能。您可以使用usecols关键字参数指定您只想阅读某些列,另请参阅https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html。例如,假设我们有以下csv表:

col1 , col2 , col3
0.5, test, 0.3 
0.7, test2, 0.1 

然后,

import numpy as np
table=np.genfromtxt(f,delimiter=',',skip_header=0,dtype='S',usecols=[0,1])

将加载前两列。然后,您可以使用制表包(https://pypi.python.org/pypi/tabulate)来很好地打印出您的表格。

print tabulate(table,headers='firstrow')

看起来像:

  col1    col2
-------  --------
    0.5  test
    0.7  test2

希望能回答你的问题