如何处理+:“decimal.decimal”和“float”在数据帧中不支持的操作数类型

2024-04-25 10:20:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据框,看起来像这样

   df A                df b
|  gmv   |          |  gmv  |
| 500.00 |          |  NaN  |
| 190.00 |          |  NaN  |
| 624.00 |          | 10.00 |

此代码a['gmv'].fillna(0) + b['gmv'].fillna(0)

返回错误unsupported operand type(s) for +: 'decimal.Decimal' and 'float'

我希望结果是这样的

    df              
|  gmv   |         
| 500.00 |         
| 190.00 |          
| 634.00 | 

有什么建议吗


Tags: and数据代码dffortype错误nan
1条回答
网友
1楼 · 发布于 2024-04-25 10:20:58

如果希望以浮点形式输出Series,请按^{}转换第一列:

c = a['gmv'].fillna(0).astype(float) + b['gmv'].fillna(0)
print (c)
0    500.0
1    190.0
2    634.0
Name: gmv, dtype: float64

如果要以十进制格式输出Series,请转换第二个数据帧:

from decimal import Decimal

c = a['gmv'].fillna(0) + b['gmv'].fillna(0).apply(Decimal)
print (c)
0    500
1    190
2    634
Name: gmv, dtype: object

print (type(c.iat[0]))
<class 'decimal.Decimal'>

相关问题 更多 >