dataframe values.tolist() datatype

Meng Qian picture Meng Qian · Jan 17, 2016 · Viewed 22.3k times · Source

I have a dataframe like this:

enter image description here

This dataframe has several columns. Two are of type float: price and change, while volme and amountare of type int. I use the method df.values.tolist() change df to list and get the data:

datatmp = df.values.tolist()
print(datatmp[0])

[20160108150023.0, 11.12, -0.01, 4268.0, 4746460.0, 2.0]

The int types in df all change to float types. My question is why do int types change to the float types? How can I get the int data I want?

Answer

Mike Müller picture Mike Müller · Jan 17, 2016

You can convert column-by-column:

by_column = [df[x].values.tolist() for x in df.columns]

This will preserve the data type of each column.

Than convert to the structure you want:

list(list(x) for x in zip(*by_column))

You can do it in one line:

list(list(x) for x in zip(*(df[x].values.tolist() for x in df.columns)))

You can check what datatypes your columns have with:

df.info()

Very likely your column amount is of type float. Do you have any NaN in this column? These are always of type float and would make the whole column float.

You can cast to int with:

df.values.astype(int).tolist()