1

Is there a Python solution similar to R's nice solution below?

# R
set.seed(1245)
array_truth <- sample(c(T, F), 10, replace = T)
array_int <- 1:10

# get the integers with False index 
> array_int[!array_truth] 

[1] 1 2 4

In R, you can use ! to negate, but I haven't come across as nice a solution in Python:

# python
string_data = pd.Series(['aardvark', 'artichoke', np.nan, 'avocado'])
null_values = string_data.isnull()
null_values

0    False
1    False
2     True
3    False
dtype: bool

The most Pythonic solution I know of is:

string_data[null_values != True]

0     aardvark
1    artichoke
3      avocado
dtype: object

If this is the best I can do, that's great, but I'm new to Python and haven't seen this specific question anywhere.

Akshat Mahajan
  • 9,543
  • 4
  • 35
  • 44
Ryan Erwin
  • 807
  • 1
  • 11
  • 30

1 Answers1

5

You have to use ~ instead of !:

>>> string_data[~string_data.isnull()]
0     aardvark  
1    artichoke
3      avocado
dtype: object

As @SethMMorton points out in comments, logical negation is usually done with not in plain Python e.g. not True returns False. ~ is the bitwise NOT operator. pandas overloads ~ to mean broadcasted logical not in these particular instances only, because Python doesn't allow overloading not.

Community
  • 1
  • 1
Akshat Mahajan
  • 9,543
  • 4
  • 35
  • 44
  • 3
    I'd like to point out that in general `not` is used in Python to indicate the logical opposite of a value, but in the specific case of numpy arrays or Pandas Dataframes/Series the `~` (complement) operator is used. – SethMMorton Apr 12 '16 at 23:31
  • @SethMMorton This is true, and I have updated my answer to reflect the same. – Akshat Mahajan Apr 12 '16 at 23:36
  • @RyanErwin If this answer helped you and correctly addresses your question, please mark it as accepted answer. Thanks :) – Akshat Mahajan Apr 12 '16 at 23:39
  • @AkshatMahajan, will do. I think they make you wait 15 min – Ryan Erwin Apr 12 '16 at 23:39
  • 1
    `~` isn't the "two's complement operator"; you probably misread the answer you linked, which talked about "two's-complement representation". `~` is the one's complement operator, or bitwise NOT. The closest thing to a "two's complement operator" is unary `-`, the arithmetic negation operator. – user2357112 Apr 12 '16 at 23:53