Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

excel - Storing values in a CSV file into a list in python

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...