【问题标题】:use series to select rows from df pandas使用系列从 df pandas 中选择行
【发布时间】:2016-04-16 21:32:56
【问题描述】:

从这个帖子继续:get subsection of df based on multiple conditions

我想根据存储在 Series 对象中的多个条件提取给定的行。

columns = ['is_net', 'is_pct', 'is_mean', 'is_wgted', 'is_sum']
index = ['a','b','c','d']
data = [['True','True','False','False', 'False'],
       ['True','True','True','False', 'False'],
       ['True','True','False','False', 'True'],
       ['True','True','False','True', 'False']]

df = pd.DataFrame(columns=columns, index=index, data=data)
df

    is_net  is_pct  is_mean is_wgted    is_sum
a   True    True    False   False   False
b   True    True    True    False   False
c   True    True    False   False   True
d   True    True    False   True    False

我的条件:

d={'is_net': 'True', 'is_sum': 'True'}
s=pd.Series(d)

预期输出:

    is_net  is_pct  is_mean is_wgted    is_sum
c   True    True    False   False   True

我的失败尝试:

(df == s).all(axis=1)


a    False
b    False
c    False
d    False
dtype: bool

当满足这两个条件时,不确定为什么 'c' 为 False。

注意,我可以达到这样的预期结果,但我宁愿使用 Series 方法。

df[(df['is_net']=='True') & (df['is_sum']=='True')]

【问题讨论】:

    标签: pandas boolean selection series multiple-conditions


    【解决方案1】:

    您可以通过为列添加子集来稍微修改您的解决方案:

    In [219]: df[(df == s)[['is_net', 'is_sum']].all(axis=1)]
    Out[219]:
      is_net is_pct is_mean is_wgted is_sum
    c   True   True   False    False   True
    

    或:

    In [219]: df[(df == s)[s.index].all(axis=1)]
    Out[219]:
      is_net is_pct is_mean is_wgted is_sum
    c   True   True   False    False   True
    

    【讨论】:

    • 感谢您的努力!
    【解决方案2】:

    由于您只有 2 个条件,我们可以sum 这些并过滤 df:

    In [55]:
    df[(df == s).sum(axis=1) == 2]
    ​
    Out[55]:
      is_net is_pct is_mean is_wgted is_sum
    c   True   True   False    False   True
    

    这是因为布尔值转换为 10 用于 TrueFalse

    In [56]:
    (df == s).sum(axis=1)
    ​
    Out[56]:
    a    1
    b    1
    c    2
    d    1
    dtype: int64
    

    【讨论】:

    • 如果 len(df.columns) 多于 2 但少于 len(df.columns) 会起作用吗?
    • 抱歉,如果您有更多条件但总条件少于列数,您能否更好地解释一下?如果是这样,这不一样吗?
    • 对不起,超过 2 个条件。太好了,我试试看。
    • IIUC 那么如果您有更多条件但您想要任何匹配至少 2 个条件的行,那么通过更改为 >=2 仍然可以使用
    • 太棒了!谢谢!
    猜你喜欢
    • 2017-01-29
    • 2017-03-28
    • 1970-01-01
    • 2017-04-22
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多