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

Pandas中按元素除法未按预期工作问题排查

问题:DataFrame按元素除法结果异常为常量

原始DataFrame数据

col1列数据:

col1
>>> 0    6.382474405435247e+08
1    2.414721440547710e+11
2    1.078680797585678e+13
3    5.234307123383891e+14
4    2.819640463840954e+16
5    1.723860035624660e+18
6    1.221906929903091e+20
7    1.024971897290708e+22
8    1.034685721591756e+24
9    1.266874815617544e+26
Name: col1 , dtype: float64

col2列数据:

col2
>>> 0    4.366546513962408e+10
1    1.652022839203982e+13
2    7.379755212750794e+14
3    3.581032068558979e+16
4    1.929046707578994e+18
5    1.179372536567603e+20
6    8.359631557019926e+21
7    7.012307736342528e+23
8    7.078764509914335e+25
9    8.667277701968806e+27
Name: call2, dtype: float64

异常现象

执行常规按元素除法操作df['col1'] / df['col2'],结果全部为同一常量,不符合预期:

>>> 0    0.014616755793226
1    0.014616755793226
2    0.014616755793226
3    0.014616755793226
4    0.014616755793226
5    0.014616755793226
6    0.014616755793226
7    0.014616755793226
8    0.014616755793226
9    0.014616755793226
dtype: float64

正常测试结果

通过手动循环计算值,或用这些值新建DataFrame计算,结果符合预期:

手动循环计算:

l1 = [6.382474405435247e+08,  2.414721440547710e+11, 1.078680797585678e+13, 5.234307123383891e+14]
l2 = [1.652022839203982e+13, 7.379755212750794e+14, 3.581032068558979e+16, 1.929046707578994e+18]

for i, j in zip(l1, l2):
    print(i, j)
    print(i / j)

新建DataFrame计算:

s = pd.DataFrame({"l1":l1, "l2":l2})
s['l1'] / s['l2'] # correct
>>>0    0.000038634298836
1    0.000327208880367
2    0.000301220647270
3    0.000271341647811

Numpy数组计算仍异常

将两列转为Numpy数组后执行除法,结果依然全为常量:

print(df['col1'].to_numpy() / df['col2'].to_numpy())
>>>
[0.01461676 0.01461676 0.01461676 0.01461676 0.01461676 0.01461676
 0.01461676 0.01461676 0.01461676 0.01461676]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:55:20