【问题标题】:pandas dataframe filter a column with a key word based on the aggregation of another column熊猫数据框根据另一列的聚合过滤带有关键字的列
【发布时间】:2020-04-04 21:16:05
【问题描述】:

假设我有以下数据框 df:

Contract_Id, date, product, qty
1,2016-08-06,a,1
1,2016-08-06,b,2
1,2017-08-06,c,2
2,2016-08-06,a,1
3,2016-08-06,a,2
3,2017-08-06,a,2
4,2016-08-06,b,2
4,2017-09-06,a,2

我试图找出每个合同 id 是否有产品 b 或产品 a 并返回 2 列。

理想输出:

Contract_Id, date, product, qty, contract_id_has_a, contract_id_has_b
1,2016-08-06,a,1,True,True
1,2016-08-06,b,2,True,True
2,2016-08-06,a,1,True,False
3,2016-08-06,a,2,True,False
4,2016-08-06,b,2,False,True

这只会返回该行是否有产品a

df[‘product’].str.contains('a', flags=re.IGNORECASE, regex=True)

我试过了:

import re 

df[‘product’].groupby([‘Contract_Id']).str.contains('a', flags=re.IGNORECASE, regex=True)

KeyError: ‘Contract_Id'

有人能解惑吗?谢谢!

【问题讨论】:

    标签: regex python-3.x pandas python-3.6


    【解决方案1】:

    为了执行分组但最后返回所有原始行的值(而不仅仅是每个组),您应该使用pd.transform 函数。然后您可以检查是否有任何组匹配,并将其设置为所有行。

    这可行:

    df['contract_id_has_a'] = df.groupby('Contract_Id')['product'].transform(lambda x: x.str.contains('a').any())
    

    【讨论】:

    • 谢谢!应该是df.groupby('Contract_Id')['product'].transform(lambda x: x.str.contains('a').any())
    猜你喜欢
    • 2014-12-27
    • 2021-12-01
    • 1970-01-01
    • 2020-08-08
    • 2020-05-05
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    相关资源
    最近更新 更多