如何根据布尔值过滤 pandas 系列?
目前我有:
s.apply(lambda x: myfunc(x, myparam).where(lambda x: x).dropna()
Run Code Online (Sandbox Code Playgroud)
我想要的只是保留myfunc返回 true 的条目。myfunc是使用第三方代码的复杂函数,并且仅对单个元素进行操作。
我怎样才能让这个更容易理解?
小智 5
您可以通过下面给出的示例代码来理解它
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)
Run Code Online (Sandbox Code Playgroud)
此代码将过滤 3 的倍数的系列数据。为此,我们只需添加过滤条件并将其应用于系列数据即可。您可以使用下面生成的输出来验证它。
样本系列数据:
0 1
1 12
2 15
3 3
4 5
5 3
6 6
7 9
8 10
9 5
dtype: int64
Run Code Online (Sandbox Code Playgroud)
条件过滤器输出:
0 False
1 True
2 True
3 True
4 False
5 True
6 True
7 True
8 False
9 False
dtype: bool
Run Code Online (Sandbox Code Playgroud)
最终需要的过滤数据:
1 12
2 15
3 3
5 3
6 6
7 9
dtype: int64
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助您了解我们如何对系列数据应用条件过滤器。
mask = s.apply(lambda x: myfunc(x, myparam))
print (s[mask])
Run Code Online (Sandbox Code Playgroud)
如果还通过一维数组更改mask过滤器中的索引值:
#pandas 0.24+
print (s[mask.to_numpy()])
#pandas below
print (s[mask.values])
Run Code Online (Sandbox Code Playgroud)
编辑:
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
Run Code Online (Sandbox Code Playgroud)
可调用的解决方案是可能的,但在我看来有点过于复杂:
a = s.loc[lambda s: s.apply(lambda x: myfunc(x, myparam))]
print (a)
1 2
2 3
dtype: int64
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4228 次 |
| 最近记录: |