Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list of strings into a numeric numpy array?

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?

like image 351
Cristian J Estrada Avatar asked Mar 08 '17 04:03

Cristian J Estrada


People also ask

How do you convert a list of strings to a list of numbers?

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.

How do you convert a list of strings to an array in Python?

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.

Can you convert a list to a NumPy array?

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.


2 Answers

you want astype

NA = NA.astype(float)
like image 145
gzc Avatar answered Sep 23 '22 12:09

gzc


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

like image 20
litepresence Avatar answered Sep 23 '22 12:09

litepresence