首页 > 解决方案 > 当我使用 df.append 填充数据框时,我输入 0 的列被存储为浮点数而不是整数

问题描述

我有一个使用 df.append, 填充数据框的循环。当我打印 DF 时,用 0 或 1 填充的列显示为浮点数,如何将它们存储为整数?

for index, row in df_from.iterrows():
    print(row)
    price=row["Close"]
    open=row["Open"]
    close=row["Close"]
    smallest=row["Low"]
    biggest=row["High"]
    bvol=row["Volume"]
    svol=0
    isvalid=1
    time=pes
    # i put a 1 in isvalis column, 
    s={'Price' : price ,'Time' : time ,'open' : open, 'close' : close, 'smallest': smallest, 'biggest': biggest, 'bvol' : bvol, 'svol': svol, 'isvalid' : 1, 'sell1' : 0,'vol1' :0,'id1':0, 'sell2' : 0,'vol2' :0,'id2':0 , 'sell3' : 0,'vol3' :0,'id3':0 ,'dummy1' : 0,'dummy2' : 0,'dummy3' :0 }

    df=df.append( s,  ignore_index=True)
    pes=pes+1
print(df)

标签: python

解决方案


当您添加字典时,在该字典中,您有一些新列,pandas 默认行为是将整数添加为浮点数。

一种解决方法是,添加所需的所有列,最后将数据类型转换为最合适的convert_dtypes()

import pandas as pd
df=pd.DataFrame({"a":[1,2.4],"b":[2,3]})
df.dtypes

添加新列“cnew”

my_map={"a":1,"b":2,"cnew":1}
df=df.append(my_map,ignore_index=True)
#df['cnew'] = df.cnew.astype('Int64') ==> this would also work
df.head(10)

转换数据类型:

df=df.convert_dtypes()
# integer operation works well too!
df.groupby(['a']).sum()

输出: 代码的结果


推荐阅读