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

问题描述 投票:0回答:7

我希望能够计算

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]

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

python arrays numpy average
7个回答
13
投票

你想要astype

NA = NA.astype(float)

10
投票

你有一个字符串列表

您创建了一个字符串数组

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

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

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


1
投票
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


1
投票

A = [float(v) for v in ['33.33', '33.33', '33.33', '33.37']]

A = np.array(['33.33', '33.33', '33.33', '33.37'], dtype=float)


1
投票

要将字符串转换为浮点数,最简单的方法是列表理解:

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)

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 函数,并且列表中的字符串必须是整数


0
投票

您可以使用

loadtxt
,它甚至可以处理包含数字的多行文本列表:

import numpy
A = ['33.33', '33.33', '33.33', '33.37']
NA = numpy.loadtxt(A)
B = ['33.33 33.33\n', '33.33 33.37\n']
NB = numpy.loadtxt(B)
© www.soinside.com 2019 - 2024. All rights reserved.