📜  Python - 将 CSV 列读入列表

📅  最后修改于: 2022-05-13 01:54:22.192000             🧑  作者: Mango

Python - 将 CSV 列读入列表

CSV 文件以纯文本形式存储表格数据(数字和文本)。文件的每一行都是一条数据记录。每条记录由一个或多个字段组成,以逗号分隔。使用逗号作为字段分隔符是此文件格式名称的来源。在本文中,我们将从 CSV 文件中读取数据到列表中。我们将使用熊猫的库将数据读入列表。

使用的文件:文件。

方法 1:使用 Pandas

在这里,我们有 read_csv()函数,它通过简单地创建它的对象来帮助读取 CSV 文件。列名可以写在这个对象中以访问特定的列,就像我们访问数组元素时所做的一样。 Pandas 库有一个名为 tolist() 的函数,可将数据转换为可根据我们的要求使用的列表。因此,我们将使用它来将列数据转换为列表。最后,我们将打印列表。

方法:



  • 导入模块。
  • 从 CSV 文件中读取数据。
  • 将其转换为列表。
  • 打印列表。

下面是实现:

Python3
# importing module
from pandas import *
 
# reading CSV file
data = read_csv("company_sales_data.csv")
 
# converting column data to list
month = data['month_number'].tolist()
fc = data['facecream'].tolist()
fw = data['facewash'].tolist()
tp = data['toothpaste'].tolist()
sh = data['shampoo'].tolist()
 
# printing list data
print('Facecream:', fc)
print('Facewash:', fw)
print('Toothpaste:', tp)
print('Shampoo:', sh)


Python3
# importing the module
import csv
 
# open the file in read mode
filename = open('company_sales_data.csv', 'r')
 
# creating dictreader object
file = csv.DictReader(filename)
 
# creating empty lists
month = []
totalprofit = []
totalunit = []
 
# iterating over each row and append
# values to empty list
for col in file:
    month.append(col['month_number'])
    totalprofit.append(col['moisturizer'])
    totalunit.append(col['total_units'])
 
# printing lists
print('Month:', month)
print('Moisturizer:', totalprofit)
print('Total Units:', totalunit)


输出:

方法二:使用csv模块

在这个方法中,我们将导入 csv 库并以读取模式打开文件,然后我们将使用 DictReader()函数读取 CSV 文件的数据。这个函数就像一个普通的阅读器,但它将信息映射到一个字典,字典的键由列名给出,所有值作为键。我们将创建空列表,以便我们可以在其中存储值。最后,我们访问键值并将它们附加到空列表中并打印该列表。

蟒蛇3

# importing the module
import csv
 
# open the file in read mode
filename = open('company_sales_data.csv', 'r')
 
# creating dictreader object
file = csv.DictReader(filename)
 
# creating empty lists
month = []
totalprofit = []
totalunit = []
 
# iterating over each row and append
# values to empty list
for col in file:
    month.append(col['month_number'])
    totalprofit.append(col['moisturizer'])
    totalunit.append(col['total_units'])
 
# printing lists
print('Month:', month)
print('Moisturizer:', totalprofit)
print('Total Units:', totalunit)

输出: