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?
The most Pythonic way to convert a list of strings to a list of ints is to use the list comprehension [int(x) for x in strings] . It iterates over all elements in the list and converts each list element x to an integer value using the int(x) built-in function.
To convert String to array in Python, use String. split() method. The String . split() method splits the String from the delimiter and returns the splitter elements as individual list items.
The simplest way to convert a Python list to a NumPy array is to use the np. array() function that takes an iterable and returns a NumPy array.
you want astype
NA = NA.astype(float)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With