追加pandas dataframe自动转换为float但想要int [英] append pandas dataframe automatically cast as float but want int

查看:223
本文介绍了追加pandas dataframe自动转换为float但想要int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让熊猫追加一个整数并保持整数数据类型?我意识到我可以在输入数据后将df.test.astype(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)

以下是输出:

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

它将整数转换为浮点数.

It is changing the integers to floats.

推荐答案

这是因为初始数据框为空.用一些整数列初始化它.

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)

我做完了

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

这篇关于追加pandas dataframe自动转换为float但想要int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆