【发布时间】:2019-04-29 16:09:12
【问题描述】:
我想使用两个单独的 Callables(一个由用户提供,一个由参数提供)在 DataFrame 中进行查找。也可以接受:使用显式语法按一个 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]
【问题讨论】:
-
过滤器是一个函数。您需要通过
filter(df)调用它:尝试df.loc[(df['C2']>5) & (filter(df))] -
谢谢@Chris!这在 filter(df) == df.loc[filter] 的假设下有效。我还没有弄清楚这是否总是正确的。
-
@MagO 错误不是由您的索引方式引起的,而是由按位与运算引起的。 @Chris 建议创建一个布尔掩码以避免
TypeError -
@MagO 另一个选项是创建一个包含可调用对象:
df.loc[lambda x: filter(x) & (x['C2'] > 5)],它使用之前创建的可调用对象
标签: python pandas pandas-groupby