简体   繁体   English

获取python csv文件的第二列作为整数数组

[英]Get second column of python csv file as array of ints

I have a csv file that is as follows: 我有一个csv文件,如下所示:

                #just want this row as array of ints
8/8/2016 0:00   15804300.00     
8/9/2016 0:00   15805850.00     
8/10/2016 0:00  15807737.50
...

I want to get just the second column of numbers (15804300.00...) as an array of integers so it's like: 我想只将数字的第二列(15804300.00 ...)作为整数数组,因此就像:

[15804300.00, 15805850.00, 15807737.50...]

I'm getting type casting errors but this is what I have so far: 我遇到类型转换错误,但这是到目前为止:

filename = 'data.csv' 
with open(filename, 'rb') as f:
    reader = csv.reader(f)
    dataList = list(reader)

    num = []
    for row in dataList:
        num.append(row[0].strip().split('\t'))   #split by tab 

Any suggestions? 有什么建议么? Is there an easier way to do this? 有没有更简单的方法可以做到这一点? Thank you! 谢谢!

If your data is tab delimited , tell the csv.reader() object to use that delimiter. 如果您的数据以制表符分隔 ,请告诉csv.reader()对象使用该分隔符。 There should not be any reason to split manually: 不应有任何理由手动拆分:

filename = 'data.csv' 
with open(filename, 'rb') as f:
    reader = csv.reader(f, delimiter='\t')
    num = [float(row[1]) for row in reader]

The list comprehension then picks out the second column of each row, converting the string to a float value. 然后,列表理解器将挑选出每一行的第二列,并将字符串转换为浮点值。

Demo: 演示:

>>> import csv
>>> demodata = BytesIO("""\
... 8/8/2016 0:00\t15804300.00
... 8/9/2016 0:00\t15805850.00
... 8/10/2016 0:00\t15807737.50
... """)
>>> with demodata as f:
...     reader = csv.reader(f, delimiter='\t')
...     num = [float(row[1]) for row in reader]
...
>>> num
[15804300.0, 15805850.0, 15807737.5]

This works 这有效

import csv
filename = 'data.csv'
with open(filename, 'rb') as f:
    reader = csv.reader(f, delimiter='\t')
    dataList = list(reader)
    num = []
    for row in dataList:
        num.append(float(row[0].strip().split(' ')[-1]))   #split with spaces, and extract the last item, as it is always the last one

    print num #[15804300.0, 15805850.0, 15807737.5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM