不正确,Python类似于R.

Rya*_*win 1 python pandas

是否有类似于下面的R的好解决方案的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
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

我所知道的最Pythonic解决方案是:

string_data[null_values != True]

0     aardvark
1    artichoke
3      avocado
dtype: object
Run Code Online (Sandbox Code Playgroud)

如果这是我能做的最好的,那很好,但我是Python的新手并没有在任何地方看到这个具体的问题.

Aks*_*jan 5

你必须使用~而不是!:

>>> string_data[~string_data.isnull()]
0     aardvark  
1    artichoke
3      avocado
dtype: object
Run Code Online (Sandbox Code Playgroud)

正如@SethMMorton在评论中指出的那样,逻辑否定通常not在普通的Python中完成,例如not True返回False.~按位NOT运算符.pandas重载~只表示not这些特定实例中的广播逻辑,因为Python不允许重载not.

  • 我想指出,通常在Python中使用`not`来表示值的逻辑相反,但在numpy数组或Pandas Dataframes/Series的特定情况下,使用`~`(补码)运算符. (3认同)