Pandas 系列链接:按布尔值过滤

Pandas Series Chaining: Filter on boolean value

如何根据布尔值筛选 pandas 系列?

目前我有:

s.apply(lambda x: myfunc(x, myparam).where(lambda x: x).dropna()

我想要的只是保留 myfunc returns 为真的条目。myfunc 是使用第 3 方代码的复杂函数,仅对单个元素进行操作。

我怎样才能让它更容易理解?

使用boolean indexing:

mask = s.apply(lambda x: myfunc(x, myparam))
print (s[mask])

如果 mask 中的索引值也被一维数组过滤:

#pandas 0.24+
print (s[mask.to_numpy()])

#pandas below
print (s[mask.values])

编辑:

s = pd.Series([1,2,3])

def myfunc(x, n):
    return x > n

myparam = 1
a = s[s.apply(lambda x: myfunc(x, myparam))]
print (a)
1    2
2    3
dtype: int64

callable 的解决方案是可能的,但在我看来有点过于复杂:

a = s.loc[lambda s: s.apply(lambda x: myfunc(x, myparam))]
print (a)
1    2
2    3
dtype: int64

您可以通过下面给出的示例代码理解它

import pandas as pd

data = pd.Series([1,12,15,3,5,3,6,9,10,5])
print(data)

# filter data based on a condition keep only rows which are multiple of 3
filter_cond = data.apply(lambda x:x%3==0)
print(filter_cond)
filter_data = data[filter_cond]
print(filter_data)

此代码将过滤 3 的倍数的系列数据。为此,我们只需设置过滤条件并将其应用于系列数据。您可以使用以下生成的输出来验证它。

样本系列数据:

0     1
1    12
2    15
3     3
4     5
5     3
6     6
7     9
8    10
9     5
dtype: int64

条件过滤输出:

0    False
1     True
2     True
3     True
4    False
5     True
6     True
7     True
8    False
9    False
dtype: bool

最终需要的过滤数据:

1    12
2    15
3     3
5     3
6     6
7     9
dtype: int64

希望这能帮助您了解我们如何对系列数据应用条件过滤器。