[英]Import CSV file and make each column its own list
I have a csv file that contains data like this with a lot of rows:我有一个 csv 文件,其中包含有很多行的数据:
2017, UNC (1), Gonzaga (1), Oregon (3), South Carolina (7)
2016, Villanova, (2), UNC (1), Oklahoma (2), Syracuse (10)
I am trying to import the file and make each column into its own list in the easiest way possible in python.我正在尝试在 python 中以最简单的方式导入文件并将每一列放入自己的列表中。
This will give you a list of columns, each column being a list of items.这将为您提供一个列列表,每列都是一个项目列表。
import pandas as pd
def get_columns(csv_file):
df = pd.read_csv(your.csv)
columns = []
for column in df:
columns += column
return columns
You can use the built in csv
module standard with every python installation.您可以在每个 python 安装中使用内置的csv
模块标准。
import csv
header1 = []
header2 = []
# so on
with open('file.csv') as csvfile:
reader = csv.DictReader(csvfile, fieldnames=['header1', 'header2', 'header3', 'header4', 'header5'])
for row in reader:
header1.append(row['header1'])
header2.append(row['header2'])
# so on
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.