Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can pandas.DataFrame have list type column?

Tags:

python

pandas

Is it possible to create pandas.DataFrame which includes list type field?

For example, I'd like to load the following csv to pandas.DataFrame:

id,scores
1,"[1,2,3,4]"
2,"[1,2]"
3,"[0,2,4]"
like image 577
Light Yagmi Avatar asked Dec 10 '15 09:12

Light Yagmi


People also ask

Can DataFrame hold lists?

Data frames are lists To access the first column of d, we find that it contains a vector (and a factor in case of column name). Note, that [[ ]] is an operator to select a list element. As data frames are lists, they will work here as well.

Can a Pandas column have different data types?

Pandas uses other names for data types than Python, for example: object for textual data. A column in a DataFrame can only have one data type. The data type in a DataFrame's single column can be checked using dtype .

How do you turn a column of a DataFrame into a list?

From the dataframe, we select the column “Name” using a [] operator that returns a Series object. Next, we will use the function Series. to_list() provided by the Series class to convert the series object and return a list.


1 Answers

Strip the double quotes:

id,scores
1, [1,2,3,4]
2, [1,2]
3, [0,2,4]

And you should be able to do this:

query = [[1, [1,2,3,4]], [2, [1,2]], [3, [0,2,4]]]
df = pandas.DataFrame(query, columns=['id', 'scores'])
print df
like image 153
Sameer Mirji Avatar answered Oct 21 '22 18:10

Sameer Mirji