+2 votes
in Programming Languages by (6.7k points)
After reading a CSV file using Pandas, I selected one of the columns of the CSV file. Now I want to convet the values in that column to a list. How can I do that?

1 Answer

0 votes
by (12.7k points)

First, use .values to get a Numpy array and then .tolist() to convert Numpy array to a list. Check the following example for the details.

>>> import pandas as pd

>>> df=pd.DataFrame({'a':[0,2,4,6,8],'b':[1,3,5,7,9]})

>>> df

   a  b

0  0  1

1  2  3

2  4  5

3  6  7

4  8  9

>>> df['a']

0    0

1    2

2    4

3    6

4    8

Name: a, dtype: int64

>>> df['a'].values

array([0, 2, 4, 6, 8])

>>> df['a'].values.tolist()

[0, 2, 4, 6, 8]

>>> df['b'].values.tolist()

[1, 3, 5, 7, 9]

 
...