如何将字符串列表转换为数字numpy数组?

Cri*_*ada 4 python arrays numpy average

我希望能够计算平均值,最小值和最大值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
Run Code Online (Sandbox Code Playgroud)

这不起作用,除非转换为:

A = [33.33, 33.33, 33.33, 33.37]
Run Code Online (Sandbox Code Playgroud)

是否可以自动执行此转换?

lit*_*nce 6

你有一个字符串列表

您创建了一个字符串数组

您需要一组浮点数进行后期处理;所以当你创建你的数组时指定数据类型,它会在创建时将字符串转换为浮点数

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
Run Code Online (Sandbox Code Playgroud)

https://docs.scipy.org/doc/numpy/user/basics.types.html