【问题标题】:TypeError when rounding up float values of a numpy array四舍五入numpy数组的浮点值时出现TypeError
【发布时间】:2019-05-15 13:06:59
【问题描述】:

给定一个由浮点值组成的 numpy 数组,例如:

floatvalues = [1.3423 , 40.331 , 3.123894,
               93.3941, 1.34, 23.59]

我使用的 numpy 数组有 8000 列和 38 行。我的目标是确定每行的最大值并将这些最大值作为向量返回。因此,我创建了 np.array 的数据框并使用了最大函数。之后,我想将最大值四舍五入为不同的小数位数(例如小数=3)。期望的结果:

0   93.395 
1   40.332 
2   23.590

因此我使用了以下代码:

import pandas as pd
import numpy as np
import math

def roundup(value, decimals=0):
    n = 10**-decimals
    return round(math.ceil(value / n) * n, decimals)

input_file = np.load("U:\\floatvalues.npy")
input_array = pd.DataFrame(input_file)
inputs_max = np.max(input_array, axis=0)

rounded_inputs_max = roundup(inputs_max, 4)
print(rounded_inputs_max)

这导致:

TypeError: cannot convert the series to <class 'float'>

所以我尝试直接访问 np.array 的最大值,而不是 DataFrame 中的最大值:

 input_file = np.load("U:\\floatvalues.npy)
 #input_array = pd.DataFrame(input_file)
 inputs_max = np.max(input_file, axis=0)

 rounded_inputs_max = roundup(inputs_max,4)
 print(rounded_inputs_max)

这导致:

TypeError: only size-1 arrays can be converted to Python scalars

最好是使用 DataFrame 的第一种方法。有人可以帮我吗?提前致谢。

【问题讨论】:

  • 为什么你不能使用np.round(inputs_max, 3) 而不是你使用的自定义函数?
  • 试试inputs_max = np.max(np.asarray(input_array), axis=0)
  • 我不能使用round函数,因为我总是想四舍五入到某个小数。这就是我使用自定义的原因。例如:1,40302 到小数点后第四位:1,4031。 @Vaibhavgusain:使用您的建议:TypeError:只有 size-1 数组可以转换为 Python 标量
  • 你能告诉错误发生在哪一行吗?
  • 第 7 行(返回)和第 13 行(调用函数的地方,rounded_inputs_max=...)

标签: python pandas numpy rounding typeerror


【解决方案1】:

这没有经过测试,尤其是对于 arr[n] 是正确舍入的地方。

In [10]: def np_roundup(arr,pl):
    ...:     factor=10**pl
    ...:     temp=arr*factor
    ...:     t_int=temp.astype(np.int32)
    ...:     rem=(temp-t_int)>0
    ...:     t_int+=rem
    ...:     return t_int/factor

可能会有更简洁的 numpy 函数。

12 月 18 日编辑
我刚刚注意到有一个 numpy ceil 函数。

def np_roundup(arr, pl):
    factor=10**pl
    return np.ceil(arr*factor)/factor

整洁很多。

HTH

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多