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



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

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 | 

有什么建议吗?

如果要在浮点中输出Series,请通过Series.astype:转换第一列

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,请转换第二个DataFrame:

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'>

最新更新