Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Value of zero in array with dtype C char evaluates to 'True' #13973

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
david-cortes opened this issue Jul 13, 2019 · 2 comments
Closed

Value of zero in array with dtype C char evaluates to 'True' #13973

david-cortes opened this issue Jul 13, 2019 · 2 comments

Comments

@david-cortes
Copy link
Contributor

david-cortes commented Jul 13, 2019

Steps to reproduce:

  • Create an array of booleans represented as integers or some other type with something that can be evaluated to Python False.
  • Convert said array to C char.
  • Interpret any of those values as boolean.

Expected behavior: values corresponding to zero should be taken as False.

Actual behavior: all values are taken as True.

Example

import numpy as np, ctypes
arr = np.array([0, 0, 1])
arr_char = arr.astype(ctypes.c_char)
bool(arr_char[0])
>>>    True
@david-cortes david-cortes changed the title 'char' Array entries always evaluate to 'True' C 'char' Array entries always evaluate to 'True' Jul 13, 2019
@david-cortes david-cortes changed the title C 'char' Array entries always evaluate to 'True' Array entries of type C 'char' always evaluate to 'True' Jul 13, 2019
@david-cortes david-cortes changed the title Array entries of type C 'char' always evaluate to 'True' Value of zero in array with dtype C char evaluates to 'True' Jul 19, 2019
@WarrenWeckesser
Copy link
Member

This is normal behavior.

Note that arr_char[0] is a numpy.bytes_ object with length 1:

In [36]: arr_char
Out[36]: array([b'0', b'0', b'1'], dtype='|S1')

In [37]: arr_char[0]
Out[37]: b'0'

The "truthiness" of a Python bytes object or a NumPy bytes_ object depends only on its length, not on the characters stored in the object; bytes objects with length 0 are False:

In [51]: bool(b'')
Out[51]: False

In [52]: bool(b'0')
Out[52]: True

In [53]: bool(np.bytes_(b''))
Out[53]: False

In [54]: bool(np.bytes_(b'0'))
Out[54]: True

@seberg
Copy link
Member

seberg commented Nov 10, 2021

Agreed with Warren, just an addendum that while this one makes sense, there are a lot of corner cases that we badly need to align with Python strings: gh-9875

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants