12

I want to be able to calculate the mean, min and max of 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

This does not work, unless converted to:

A = [33.33, 33.33, 33.33, 33.37]

Is it possible to perform this conversion automatically?

MB-F
  • 22,770
  • 4
  • 61
  • 116
Cristian J Estrada
  • 357
  • 2
  • 3
  • 14

6 Answers6

13

you want astype

NA = NA.astype(float)
gzc
  • 8,180
  • 8
  • 42
  • 62
9

You had a list of strings

You created an array of strings

You needed an array of floats for post processing; so when you create your array specify data type and it will convert strings to floats upon creation

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

litepresence
  • 3,109
  • 1
  • 27
  • 35
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)

Output: 33.34 33.37 33.33

Serenity
  • 35,289
  • 20
  • 120
  • 115
1

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

or

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

yama3
  • 11
  • 3
1

To convert your strings to floats, the simplest way is a list comprehension:

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

Now you can convert to an array:

array_A = np.array(floats)

The rest is probably known to you:

mean, min, max = np.mean(array_A), np.min(array_A), np.max(array_A)
chthonicdaemon
  • 19,180
  • 2
  • 52
  • 66
0

Here it is:

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)

Hope this helps!!! Basically, you didn't have the functions for min and max and your strings in the list had to be integers