gpt4 book ai didi

python - 不正确,Python 类似于 R

转载 作者:太空宇宙 更新时间:2023-11-04 08:49:48 24 4
gpt4 key购买 nike

有没有类似于下面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 .

关于python - 不正确,Python 类似于 R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36585860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com