append pandas dataframe 自动转换为 float 但需要 int

append pandas dataframe automatically cast as float but want int

如何让 pandas 附加一个整数并保持整数数据类型?我意识到在输入数据后我可以 df.test.astype(int) 到整个列,但如果我在附加数据时可以这样做,那似乎是更好的方法。这是一个示例:

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

它正在将整数更改为浮点数。

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

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)

如本期所述:df.append should retain columns type if same type #18359append 方法将保留自 pandas 0.23.0.

以来的列类型

因此将 pandas 版本升级到 0.23.0 或更新版本可以解决这个问题。

嗯,我发现有 2 个解决方法。

  1. 升级到pandas版本>= 0.23.0

  2. 但是如果无法更改 pandas 版本,例如在生产代码工作时,版本更改可能会影响 prod 环境中的其他 scripts/codes。 所以下面 one-liner 是一个快速的解决方法。

df = df.astype(int)

如果您使用 Pandas 1.0.0 及更高版本,则需要使用 convert_dtypes。参考 link 的描述和使用 convert_dtypes

df = df.convert_dtypes()
df = df.append({'test':test, 'another':5}, ignore_index=True)