【问题标题】:Get specific column from csv file in python从python中的csv文件获取特定列
【发布时间】:2018-05-16 23:29:52
【问题描述】:

我是 python 编程的新手,我有一个关于从 csv 文件读取的问题。 我想要做的是将我的 csv 文件分成 2 个并保存在两个列表中。 所以形成我的下一个 csv 文件:

    5.1,3.5,1.5,0.2,setosa
    4.9,3.0,1.4,0.2,setosa
    4.6,3.1,1.5,0.2,setosa

我需要我的列表看起来像:

firstList = [ [5.1, 3.5, 1.5, 0.2], [4.9, 3.0, 1.4, 0.2], [4.6, 3.1, 1.5, 0.2] ]
secondList = ['setosa', 'setosa', 'setosa']

我尝试了不同的时间,但最接近的结果是下一个:

firstList = []
secondList = []

with open('file.csv') as file:
    fileReader = csv.reader(file, delimiter=',')
    for row in fileReader:
        firstList.append(row)
        secondList.append(row[4])

这个的输出是:

firstList = [ ['5.1', '3.5', '1.5', '0.2', 'setosa'], ['4.9', '3.0', '1.4', '0.2', 'setosa'], ['4.6', '3.1', '1.5', '0.2', 'setosa'] ]
secondList = ['setosa', 'setosa', 'setosa']

我只想从我的 firstList 中删除字符串 'setosa' 并将其他所有内容都转换为 int 任何帮助将不胜感激。 谢谢!

【问题讨论】:

    标签: python csv


    【解决方案1】:

    您可以构建该行中前三个单元格的子列表,然后在从它们创建新列表时构建浮动。

    firstList = []
    secondList = []
    
    with open('file.csv') as file:
        fileReader = csv.reader(file, delimiter=',')
        for row in fileReader:
            firstList.append([float(cell) for cell in row[:3]])
            secondList.append(row[4])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-22
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 1970-01-01
      相关资源
      最近更新 更多