【问题标题】:How to read strings from a csv file and convert it into a integer array?如何从 csv 文件中读取字符串并将其转换为整数数组?
【发布时间】:2021-05-23 09:36:47
【问题描述】:

我正在寻找借助 csv 文件中的数据创建整数数组的最优化方法。

csv 文件("sample.csv") 数据是这样的,

prediciton1 prediction2 prediction3
low low low
low high high

其中 = 1, = 3,

我想从 csv 中读取这些数据并制作一个如下所示的数组,

array =  
[[1,1,1],  
[1,3,3]]

    import csv
    import sys
    
    num1 = 'low'
    num2 = 'high'
    
    
    csv_file = csv.reader(open('sample.csv', "r"), delimiter=",")
    
    count = 0
    
    for row in csv_file:
    
        if count == 1:
            if num1 == row[0]:
                dat1 = 1
        
            elif num2 == row[0]:
                dat1 = 3
            if num1 == row[1]:
                dat2 = 1
        
            elif num2 == row[1]:
                dat2 = 3
                
            if num1 == row[2]:
                dat3 = 1
        
            elif num2 == row[2]:
                dat3 = 3
        
            
        count = count + 1

    array =[dat1,dat2,dat3]

这种方法有效,但似乎效率低下。寻找替代和优化的方法来实现这一目标。

【问题讨论】:

    标签: python string csv integer


    【解决方案1】:

    使用dict 进行查找和列表理解

    例如:

    check = {'low': 1, "high": 3}
    
    with open('sample.csv') as infile:
        csv_file = csv.reader(infile)
        next(csv_file) # skip header
        result = [[check[c] for c in row] for row in csv_file]
    

    【讨论】:

    • 漂亮干净的解决方案!我只想补充一点,以防 CSV 包含不需要的值(因为它有时可能会发生)我会使用 check.get(c) 而不是 check[c] 并稍后处理 None 包含在 result 数组中的潜在值。
    【解决方案2】:

    由于 CSV 文件非常简单,您甚至可以不使用 CSV 包:

    # We open the CSV file
    with open('sample.csv') as file:
        # We read all the lines and store them in a list
        lines = file.readlines()
    
    # We remove the CSV header
    lines = lines[1:]
    
    # We create the array
    array = [
        [{
            'low': 1,
            'high': 3
        }.get(value.strip()) for value in line.split(',')
    ] for line in lines]
    
    # We print the array
    print(array)
    

    这将打印以下数组:[[1, 1, 1], [1, 3, 3]]

    注意使用dictget 方法来避免错误,以防万一CSV 包含不需要的值。在这些情况下,该数组将包含一个 None 值。

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 2015-08-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多