2016-11-09 80 views
3

如何讓熊貓追加一個整數並保留整型數據類型?我意識到我可以將df.test.astype(int)添加到整個列中,但是如果我在添加數據時能夠做到這一點,那麼這似乎是更好的方法。下面是一個示例:追加熊貓數據框自動轉換爲浮點數,但想要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 

它改變整數浮動。

回答

3

這是因爲你的初始數據幀是空的。用一些整數列初始化它。

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


如果我做

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

enter image description here

+0

是有可能做到每列不同dtypes? – kaminsknator