【问题标题】:How to convert columns from a csv file into arrays in python with the first value being the array variable name?python - 如何将csv文件中的列转换为python中的数组,第一个值为数组变量名?
【发布时间】:2019-09-30 20:15:39
【问题描述】:

我想将我的 csv 文件中的列转换为 python 中的数组,但是我希望每列(第一行)中的第一个值是数组名称。

我试过这个:

import csv

data = csv.reader(open('products.csv', 'r'), delimiter=",", quotechar='|')
column1, column2 = [], []

for row in data:
    column1.extend(row[0])
    column2.extend(row[1])

print(column1)
print(column2)

但是,这会逐个字符地赋予它,并且不会使数组名称成为第一个值。

这是我的 csv 文件。

name,description,price
Apples,A bag of 3 apples,1.75
White Bread,A loaf of white bread,1.90
Wholemeal Bread,A loag of wholemeal bread,1.45

它需要是可扩展的(不是硬编码/我稍后会添加到这个文件中)

预期结果是 3 个数组。

name = []
description = []
price = []

并且值排成一行,例如所有数组中的索引 0 将是第一列等。

【问题讨论】:

    标签: python arrays csv


    【解决方案1】:

    我强烈建议为此使用 Pandas DataFrame。做

    pip3 install pandas
    

    然后在你的python代码中,

    import pandas as pd
    
    df = pd.read_csv('products.csv')
    

    在交互式 python 控制台中,您可以探索此 DataFrame 的结构

    %% Get the 'name' column
    df['name']
    
    %% Get the 'description' column
    description = df['description']
    
    %% Get it in a numpy array
    description = df['description'].values
    
    %% Get the row named 'Apples'
    Apples = df[df['name'] == 'Apples']
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      如果您在 csv 文件中有大量样本并且不想构造 DataFrame 对象,则可以使用 csv 模块并以可迭代的方式构造您的列表,而无需将整个数据加载到内存中:

      import csv
      
      csv_file = 'sample.csv'
      
      names = []
      description = []
      price = []
      
      with open(csv_file, 'r') as f:
          reader = csv.DictReader(f)
          for row in reader:
              names.append(row.get('name'))
              description.append(row.get('description'))
              price.append(row.get('price'))
      
      print(names)
      ## ['Apples', 'White Bread', 'Wholemeal Bread']
      
      print(description)
      ## ['A bag of 3 apples', 'A loaf of white bread', 'A loag of wholemeal bread']
      
      print(price)
      ## ['1.75', '1.90', '1.45']
      

      【讨论】:

        【解决方案3】:

        假设 csv 是

        A, B, C
        1, a, x
        2, b, y
        3, c, z
        

        您可以使用exec 在更大的列表中设置您需要的所有变量。

        假设列表已经如下构造

        [[1, 2, 3], [a, b, c], [x, y, z]] # This should be fairly straightforward.
        
        # data is the lists
        # row is the first row
        for i in range(len(row)):
           exec(row[i] + " = " + str(data[i]))
        
        # Now all the variables should be defined 
        # >>> A
        # [1, 2, 3]
        # ...
        

        【讨论】:

        • 你知道在我的代码示例中如何构造row和data吗?
        猜你喜欢
        • 2019-08-08
        • 2020-02-18
        • 2018-02-18
        • 1970-01-01
        • 1970-01-01
        • 2017-02-13
        • 2017-01-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多