有没有类似于下面R的nice解决方案的Python解决方案?
# 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
在 R 中,你可以使用 ! 来取反,但我还没有在 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
我所知道的最 Pythonic 的解决方案是:
string_data[null_values != True]
0 aardvark
1 artichoke
3 avocado
dtype: object
如果这是我能做的最好的,那很好,但我是 Python 的新手,还没有在任何地方看到这个具体问题。
请您参考如下方法:
你必须使用 ~ 而不是 !:
>>> string_data[~string_data.isnull()]
0 aardvark
1 artichoke
3 avocado
dtype: object
正如@SethMMorton 在评论中指出的那样,逻辑否定通常在纯 Python 中使用 not 完成,例如not True 返回 False。 ~ 是 bitwise NOT operator . pandas 重载 ~ 仅在这些特定实例中表示广播逻辑 not,因为 Python 不允许重载 not .
