【发布时间】: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