syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Python how do I create a list from Pandas?

I am currently working with some data which requires that I copy data from a column in a Pandas DataFrame into a plain Python List.

We have several ways to do this copy.

I prefer to copy the column into a Numpy Array and then use a python-comprehension to build the list from array elements:
# df2list.py
import pandas as pd
mydf = pd.read_csv('/tmp/spydata.csv')
print(mydf.head())
myarray = mydf[['cp']].values
mylist  = [acp[0] for acp in myarray]
print(mylist[0:5])


Screen Dump:

dan@hp /a/ks/knnspy $ 
dan@hp /a/ks/knnspy $ python
Python 2.7.9 |Anaconda 2.1.0 (64-bit)| (default, Dec 12 2014, 14:52:24) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
>>> 
>>> import pandas as pd
>>> mydf = pd.read_csv('/tmp/spydata.csv')
>>> print(mydf.head())
        ydate     opn     hgh      lo      cp        vol    adjc
0  2014-12-31  207.99  208.19  205.39  205.54  123713700  205.54
1  2014-12-30  208.21  208.37  207.51  207.60   73540800  207.60
2  2014-12-29  208.22  208.97  208.14  208.72   79643900  208.72
3  2014-12-26  208.31  208.85  208.25  208.44   57326700  208.44
4  2014-12-24  208.02  208.34  207.72  207.77   42963400  207.77
>>> myarray = mydf[['cp']].values
>>> mylist  = [acp[0] for acp in myarray]
>>> print(mylist[0:5])
[205.53999999999999, 207.59999999999999, 208.72, 208.44, 207.77000000000001]
>>> 
>>> quit()
dan@hp /a/ks/knnspy $ 
dan@hp /a/ks/knnspy $ 


syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me