在Python中把 CSV 文件读成一个列表
在这篇文章中,我们将看到如何在 Python 中把 CSV 文件读成一个列表。
方法1:使用CSV模块
- 我们可以将CSV文件读成不同的数据结构,如列表、图元列表或字典列表。
- 我们可以使用其他模块,如pandas,这些模块大多用于ML应用,涵盖了将CSV内容导入到有或无标题的列表中的场景。
示例 1:
在这个例子中,我们正在读取一个CSV文件并将字符串转换为列表。
import csv
with open('sample.csv', 'r') as read_obj:
# Return a reader object which will
# iterate over lines in the given csvfile
csv_reader = csv.reader(read_obj)
# convert string to list
list_of_csv = list(csv_reader)
print(list_of_csv)
输出:
[[‘JAN’, 34, 360, 417], [‘FEB’, 31, 342, 391], [‘MAR’, 36, 406, 419], [‘APR’, 34, 396, 461],
[‘MAY’, 36, 420, 472], [‘JUN’, 43, 472, 535], [‘JUL’, 49, 548, 622], [‘AUG’, 50, 559, 606],
[‘SEP’, 40, 463, 508], [‘OCT’, 35, 407, 461], [‘NOV’, 31, 362, 390], [‘DEC’, 33, 405, 432]]
示例 2:
在这个例子中,我们正在读取一个CSV文件,并在给定的CSV中迭代行。
import csv
with open('example.csv') as csvfile:
# Return a reader object which will
# iterate over lines in the given csvfile.
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
print(row)
print(row[0])
print(row[0], row[1], row[2],)
print("\n")
输出:
方法2:使用Pandas
你可以使用pandas库,它有一个内置的方法将数值转换为一个列表。Pandas.values属性用于获取numpy.array,然后使用tolist()函数将该数组转换为列表。
注意:更多信息请参考使用Pandas将CSV读成列表。
# app.py
import pandas as pd
# Creating Dictionary
dict = {
'series': ['Friends', 'Money Heist', 'Marvel'],
'episodes': [200, 50, 45],
'actors': [' David Crane', 'Alvaro', 'Stan Lee']
}
# Creating Dataframe
df = pd.DataFrame(dict)
print(df)
输出:
极客教程