将CSV文件中的值存储到python中的列表中 [英] Storing values in a CSV file into a list in python
问题描述
我想创建一个存储单个列所有值的列表. 例如,假设我的文件中有一个名为"FirstNames"的列,而对于前三行,名称"列中有Merry,Pippin和Frodo.
I'd like to create a list that stores all values of a single column. For example let's say my file has a column called 'FirstNames' and for the first 3 rows, the 'names' column has Merry, Pippin, Frodo.
我想创建一个看起来像[Merry,Pippin,Frodo]的列表
I'd like to create a list that looks like [Merry, Pippin, Frodo]
我试图这样做:
import pandas as pd
data = pd.read_csv(".../TrainingFile.csv")
list = []
names = data['FirstNames']
for i in range(0,2):
list.append(names[i:i+1])
print(list)
但是,列表不仅将值存储在单元格中,而且给了我这样的输出:
However the list does not only store the values in the cells and gives me an output like this:
名称:名字,dtype:对象,1快活
Name: FirstName, dtype: object, 1 Merry
名称:名字,dtype:对象,2个Pippin
Name: FirstName, dtype: object, 2 Pippin
名称:名字,dtype:对象,3个Frodo
Name: FirstName, dtype: object, 3 Frodo
我该如何更改?感谢您的帮助.
How can I change this? Thanks for the help.
奖金:我不是如何定义range(0,2),而是通过文件中的行数来定义范围?
Bonus: instead of range(0,2) how can I define the range so that it goes through the number of rows there are in the file?
推荐答案
请不要使用诸如list
,type
,id
...之类的保留字作为变量,因为它们会掩盖内置函数.
Please never use reserved words like list
, type
, id
... as variables because masking built-in functions.
如果稍后在代码中使用list
,例如
If later in code use list
e.g.
list = data['FirstNames'].tolist()
#another solution for converting to list
list1 = list(data['SecondNames'])
出现非常奇怪的错误,调试非常复杂.
get very weird errors and debug is very complicated.
所以需要:
L = data['FirstNames'].tolist()
或者:
L = list(data['FirstNames'])
还可以检查在我的代码中使用python单词"type"是否安全.
这篇关于将CSV文件中的值存储到python中的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!