【发布时间】: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