kam*_*tor 8 python bitstring dataframe pandas
如何让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)
Run Code Online (Sandbox Code Playgroud)
这是输出:
1
0 1.0
Name: test, dtype: float64
0 5.0
Name: another, dtype: float64
Run Code Online (Sandbox Code Playgroud)
它将整数更改为浮点数.
这是因为您的初始数据帧是空的.用一些整数列初始化它.
df = pd.DataFrame(dict(A=[], test=[], another=[]), dtype=int)
df.append(dict(A=3, test=4, another=5), ignore_index=True)
Run Code Online (Sandbox Code Playgroud)
我做完了
df = pd.DataFrame()
df.append(dict(A=3, test=4, another=5), ignore_index=True)
Run Code Online (Sandbox Code Playgroud)