Storing values in a CSV file into a list in python

2019-09-21 19:23发布

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.

I'd like to create a list that looks like [Merry, Pippin, Frodo]

I tried doing it like this:

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:

Name: FirstName, dtype: object, 1 Merry

Name: FirstName, dtype: object, 2 Pippin

Name: FirstName, dtype: object, 3 Frodo

How can I change this? Thanks for the help.

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?

2条回答
趁早两清
2楼-- · 2019-09-21 19:36

Because you are using reserved variable names. Instead of using list, use list1 or something else as the variable name.

Few of the reserved variable names in python are: dict, str, list, int, pass etc, which we use mistakenly. Try to avoid it.

查看更多
Explosion°爆炸
3楼-- · 2019-09-21 19:45

Please never use reserved words like list, type, id... as variables because masking built-in functions.

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.

So need:

L = data['FirstNames'].tolist()

Or:

L = list(data['FirstNames'])

Also can check Is it safe to use the python word “type” in my code.

查看更多
登录 后发表回答