You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用loc向DataFrame末尾添加行后数据类型变为float的原因

问题场景

初始创建DataFrame的代码如下:

import pandas as pd
data = {"score":[10, 54, 65, 23, 94, 40, 79, 89], "code":[2, 6, 8, 6, 4, 9, 1, 5], "percentage":[0.12, 0.65, 0.03, 0.96, 0.43, 0.76, 0.23, 0.93]}
df = pd.DataFrame(data)
print(df)

输出结果:

score  code  percentage
0     10     2        0.12
1     54     6        0.65
2     65     8        0.03
3     23     6        0.96
4     94     4        0.43
5     40     9        0.76
6     79     1        0.23
7     89     5        0.93

使用loc向DataFrame末尾添加一行数据:

df.loc[len(df)] = [43, 9, 0.55]
print(df)

输出后发现score和code列的数据类型变为了float:

score  code  percentage
0   10.0   2.0        0.12
1   54.0   6.0        0.65
2   65.0   8.0        0.03
3   23.0   6.0        0.96
4   94.0   4.0        0.43
5   40.0   9.0        0.76
6   79.0   1.0        0.23
7   89.0   5.0        0.93
8   43.0   9.0        0.55

请问出现该现象的原因是什么?

原因分析
  • 用df.loc[len(df)] = [43, 9, 0.55]添加行时,Pandas会先把传入的列表转换成Series。由于列表里包含浮点数0.55,整个Series的类型会被统一提升为float——因为float可以兼容整数,整数却无法兼容浮点数。
  • 当把这个float类型的Series赋值给DataFrame时,原DataFrame中score和code列的整数类型会被向上转换为float,以此保证整列数据类型一致,避免类型冲突。
避免类型转换的解决方法

如果想保留原列的整数类型,可以用以下两种方式:

  1. 使用pd.concat拼接新行:
new_row = pd.DataFrame({"score":[43], "code":[9], "percentage":[0.55]})
df = pd.concat([df, new_row], ignore_index=True)
  1. 按原列类型构造新Series后再添加:
df.loc[len(df)] = pd.Series([43, 9, 0.55], index=df.columns, dtype={'score':int, 'code':int, 'percentage':float})

内容的提问来源于stack exchange,提问作者mohsenet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:51:32