我想在DataFrame中使用两个独立的Callable(一个由用户提供,一个由param提供)进行查找。也可以接受。通过一个Callable和另一个使用显式语法的过滤器进行索引。
这可能吗?我猜测可以用groupby来实现,但这似乎有点麻烦。
最小的代码示例。
import pandas as pd # Version: 0.23.4, Python 2.7
df = pd.DataFrame({'C1': [1, 2,1], 'C2': [3, 4, 10]})
# This works
filter = lambda adf: adf['C1']==1
df.loc[filter]
# So does this
df.loc[df['C2']>5]
# Both of them together works
df.loc[(df['C2']>5) & (df['C1']==1)]
# So why don't any of these?
df.loc[(df['C2']>5) & filter] #TypeError: ...
df.loc[(df['C2']>5) & (filter)] # TypeError: ...
df.loc[df['C2']>5 & filter] # TypeError: ...
filter2 = lambda adf: adf['C2']>5
df.loc[(filter) & (filter2)] # TypeError: ...
df.loc[(filter) | (filter2)] # TypeError: ...
# Nesting works, but isn't pretty for multiple callables
df.loc[(df['C2']>5)].loc[filter]
当你通过你的lambda filter
作为 loc
参数,你是像传递一个对象函数一样传递它,而不是作为该函数的计算结果。
出于这个原因,你不能使用任何 logical operator
来组合多个函数,这与使用多个 logical
标准。
在任何情况下,如果你想使用异质标准(逻辑和功能)来过滤你的数据框架,你可以使用 loc
两次,就像你自己说的那样
# function
filter = lambda df: df['C1']==1
df.loc[(df['C2']>5)].loc[filter]