0

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?

1
  • you can see the dtype of an array using dtype method: arr.dtype Commented May 1, 2022 at 20:41

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.