The Python Oracle

What happened to python's ~ when working with boolean?

This video explains
What happened to python's ~ when working with boolean?

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping

--

Chapters
00:00 Question
01:22 Accepted answer (Score 16)
02:26 Thank you

--

Full question
https://stackoverflow.com/questions/5607...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pandas #boolean

#avk47



ACCEPTED ANSWER

Score 16


Ah , since you created the c by using DataFrame constructor , then T,

1st let us look at what we have before T:

pd.DataFrame([a, b])
Out[610]: 
      0     1     2     3     4      5      6      7      8      9
0     a     a     a     a     b      a      b      b      b      b
1  True  True  True  True  True  False  False  False  False  False

So pandas will make each columns only have one dtype, if not it will convert to object .

After T what data type we have for each columns

The dtypes in your c :

c.dtypes
Out[608]: 
Classification    object
Boolean           object

Boolean columns became object type , that is why you get unexpected output for ~c.Boolean


How to fix it ? ---concat

c=pd.concat([a,b],1)
c.columns = ['Classification', 'Boolean']
~c.Boolean
Out[616]: 
0    False
1    False
2    False
3    False
4    False
5     True
6     True
7     True
8     True
9     True
Name: Boolean, dtype: bool