繁体   English   中英

df.loc[] 具有多个可调用对象

[英]df.loc[] with multiple callables

我想使用两个单独的 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]

当您将 lambda filter作为loc参数传递时,您将其作为对象函数传递,而不是作为该函数计算的结果。

出于这个原因,您不能使用任何logical operator来组合多个函数,这与使用多个logical条件时发生的情况不同。

在任何情况下,如果您想使用异构标准(逻辑和功能)来过滤数据框,您可以使用loc两次。 正如你自己建议的那样。

# function
filter = lambda df: df['C1']==1
df.loc[(df['C2']>5)].loc[filter]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM