python - 当我使用 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)
解决方案
当您添加字典时,在该字典中,您有一些新列,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()
输出: 代码的结果
推荐阅读
- reactjs - 带有按钮的 React Native FlatList 过滤器
- javascript - 将整数上的千数替换为 0
- python - 我可以改进这个 django 模型结构吗?
- c++ - 模板模板参数替换失败
- r - RShiny:在 Shiny 中创建 .docx 文件时出现问题
- python - 您如何将不规则张量与 tf.data 和 TFRecords 一起使用?
- performance - 如何在 Chrome 中测量渲染时间 1000 次?
- java - 从 RecyclerView 作为字符串接收的数组中的 ListView
- haskell - Haskell:按字典顺序对 3 个元组的第一个元素进行排序的函数
- python - 如何获得二维列表查找计数python?