kaminsknator kaminsknator - 23 days ago 12
Python Question

append pandas dataframe automatically cast as float but want int

How do I get pandas to append an integer and keep the integer data type? I realize I can df.test.astype(int) to the entire column after I have put in the data but if I can do it at the time I'm appending the data it seems like that would be a better way. Here is a sample:

from bitstring import BitArray
import pandas as pd
df = pd.DataFrame()

test = BitArray('0x01')
test = int(test.hex)
print(test)
df = df.append({'test':test, 'another':5}, ignore_index=True)

print(df.test)
print(df.another)


Here is the output:

1
0 1.0
Name: test, dtype: float64
0 5.0
Name: another, dtype: float64


It is changing the integers to floats.

Answer

It's because your initial dataframe is empty. Initialize it with some integer column.

df = pd.DataFrame(dict(A=[], test=[], another=[]), dtype=int)
df.append(dict(A=3, test=4, another=5), ignore_index=True)

enter image description here


Had I done

df = pd.DataFrame()
df.append(dict(A=3, test=4, another=5), ignore_index=True)

enter image description here

Comments