我希望能够计算A
的平均值,最小值和最大值:
import numpy as np
A = ['33.33', '33.33', '33.33', '33.37']
NA = np.asarray(A)
AVG = np.mean(NA, axis=0)
print AVG
这不起作用,除非转换为:
A = [33.33, 33.33, 33.33, 33.37]
是否可以自动执行此转换?
答案 0 :(得分:6)
你想要astype
NA = NA.astype(float)
答案 1 :(得分:4)
你有一个字符串列表
您创建了一个字符串数组
你需要一系列花车进行后期处理;所以在创建数组时指定数据类型,它会在创建时将字符串转换为浮点数
import numpy as np
#list of strings
A = ['33.33', '33.33', '33.33', '33.37']
print A
#numpy of strings
arr = np.array(A)
print arr
#numpy of float32's
arr = np.array(A, dtype=np.float32)
print arr
#post process
print np.mean(arr), np.max(arr), np.min(arr)
>>>
['33.33', '33.33', '33.33', '33.37']
['33.33' '33.33' '33.33' '33.37']
[ 33.33000183 33.33000183 33.33000183 33.36999893]
33.34 33.37 33.33
答案 2 :(得分:2)
import numpy as np
A = ['33.33', '33.33', '33.33', '33.37']
# convert to float
arr = np.array(map(float, A))
# calc values
print np.mean(arr), np.max(arr), np.min(arr)
输出:
33.34 33.37 33.33
答案 3 :(得分:2)
A = np.array(['33.33', '33.33', '33.33', '33.37'], dtype=float)
或
C:\Users\yourname\.android
答案 4 :(得分:2)
要将字符串转换为浮点数,最简单的方法是列表解析:
A = ['33.33', '33.33', '33.33', '33.37']
floats = [float(e) for e in A]
现在您可以转换为数组:
array_A = np.array(floats)
其余的可能是您所知道的:
mean, min, max = np.mean(array_A), np.min(array_A), np.max(array_A)
答案 5 :(得分:0)
这是:
import numpy as np
A = ["33.33", "33.33", "33.33", "33.37"]
for i in range(0,len(A)):
n = A[i]
n=float(n)
A[i] = n
NA = np.asarray(A)
AVG = np.mean(NA, axis=0)
maxx = max(A)
minn = min(A)
print (AVG)
print (maxx)
print (minn)
希望这会有所帮助!!! 基本上,你没有min和max的函数,列表中的字符串必须是整数