Append pandas dataframe is automatically displayed as float but wants int

How do I get pandas to add an integer and save an integer data type? I understand that I can df.test.astype (int) into the entire column after entering the data, but if I can do this while I am adding the data, it seems like this will be the best way. Here is an example:

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 result:

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

It changes integers to float.

+6
source share
3 answers

This is because your original data frame 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


If i did

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

enter image description here

+5
source

: df.append , # 18359, append pandas 0.23.0.

, Pandas 0.23.0 .

0

Well, there are 2 workarounds I found.

  1. Upgrading to pandas Version >= 0.23.0

  2. But if you cannot change the version of pandas, for example, when working with working code, changing the version may affect other scripts / codes in the environment prod. therefore below one line is a quick workaround.

df = df.astype(int)

0
source

Source: https://habr.com/ru/post/1660331/


All Articles