【问题标题】:TypeError: cannot convert the series to <class 'float'> when using math.ceilTypeError:使用 math.ceil 时无法将系列转换为 <class 'float'>
【发布时间】:2020-09-09 08:59:16
【问题描述】:

我的数据是这样的:

    order_number    ship_distance   delivery_fee    utilization remaining_multiplier_type
     R000001943        3.818           11.25            LOW            DISCOUNT
     R000002604        5.993           7.00             NaN            NaN
     R000005277        2.942           7.00             NaN            NaN
     R000006010        8.289           9.50             NaN            NaN
     R000010127        3.233           6.00             NaN            BASE

我正在尝试使用数学和 numpy 对列 ship_distance 中的值进行四舍五入。

使用data = math.ceil(data[ship_distance'] 我得到错误TypeError: cannot convert the series to &lt;class 'float'&gt; 当使用data = np.ceil(data['ship_distance']) 时,我没有得到想要的结果。

预期结果:

 order_number   ship_distance   delivery_fee    utilization   remaining_multiplier_type 
  R000001943          4            11.25             LOW           DISCOUNT                  
  R000002604          6            7.00              NaN           NaN                       
  R000005277          3            7.00              NaN           NaN                       
  R000006010          9            9.50              NaN           NaN                       
  R000010127          4            6.00              NaN           BASE                      

【问题讨论】:

标签: python python-3.x pandas numpy math


【解决方案1】:

使用 numpy:

np.ceil(df["ship_distance"]).astype("int64")

【讨论】:

  • 试过...但我没有给我想要的结果...得到以下结果 27 3.0 1453 13.0 1630 17.0 1857 5.0 2016 1.0 名称:ship_distance,dtype:float64
【解决方案2】:
# np.ceil(data['ship_distance'])
data['ship_distance'] = data['ship_distance'].apply(lambda X: int(math.ceil(X)))

print(data)

【讨论】:

  • 谢谢...它有效..为什么我应该使用 lambda?你介意解释一下吗?
  • 要将 float 转换为 int,我使用了 lambda,或者您也可以尝试 .astype() 方法来转换整个 pandas 列数据类型。
  • 这里实际上不需要 lambda:math.ceil 已经是一个接受浮点数并将上限作为int 返回的函数,所以data['ship_distance'].apply(math.ceil) 就足够了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
  • 2017-10-16
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
相关资源
最近更新 更多