I have a single numpy array:
arr = np.array([1, "sd", 3.6])
I want to detect the cells with string type values.
This:
res = arr == type(str)
returns all false.
Any help?
CodePudding user response:
import numpy as np
arr = np.array([1, "sd", 3.6])
You'll notice that the values in this array are not numerics and strings, they're just strings.
>>> arr
array(['1', 'sd', '3.6'], dtype='<U32')
You'll also note that they're not python strings. There is a reason for this but it isn't important here.
>>> type(arr[1])
<class 'numpy.str_'>
>>> type(arr[1]) == type(str)
False
You should not try to mix data types like you are doing. Use a list instead. The difference in data types that you have in your input list is lost when you turn it into an array. I note that you're calling an array element a 'cell' - it isn't, arrays don't work like spreadsheets.
That said, if you absolutely must do this:
arr = np.array([1, "sd", 3.6], dtype=object)
>>> arr
array([1, 'sd', 3.6], dtype=object)
This will keep all the array elements as python objects instead of using numpy dtypes.
>>> np.array([type(x) == str for x in arr])
array([False, True, False])
Then you can test the type of each element accordingly.
CodePudding user response:
You better to do it before doing the conversion from list like this since otherwise all the array elements are changed to same data type (for example str
here)
arr = [1, "sd", 3.6]
[type(x)for x in arr]
Output:
[int, str, float]