我有两个表:Df_exclude有不应该一起提供给同一客户的产品,即在0索引处的product1和product2不应该提供给同一客户:
product1 | product2 | 565043 | 5649965 |
---|---|
5649585 | 5649910 |
5649585 | 5649921 |
5649607 | 5649931 |
5649607 | 5649929 |
我是这样做的
df=pd.DataFrame({'product1':[1277,3921,1277,3921],'product2':[1854,2561,9132,5143]})
product1 product2
0 1277 1854
1 3921 2561
2 1277 9132
3 3921 5143
df2=pd.DataFrame({'customer':['a1','a1','a1','a2','a2','a2'],'products':[1277,1854,9132,1277,1853,9332,]})
customer products
0 a1 1277
1 a1 1854
2 a1 9132
3 a2 1277
4 a2 1853
5 a2 9332
def fun(h):
return list(h)
df2=df2.groupby('customer').agg(fun)
products
customer
a1 [1277, 1854, 9132]
a2 [1277, 1853, 9332]
validcustomer=[]
for x in range(len(df2)):
temp=df2.iloc[x].products
c=0
for y in range(len(df)):
if df.iloc[y].product1 in temp and df.iloc[y].product2 in temp:
c=1
validcustomer.append(False)
break
if c==0:
validcustomer.append(True)
df2["validity"]=validcustomer
products validity
customer
a1 [1277, 1854, 9132] False
a2 [1277, 1853, 9332] True
我所做的完全是蛮力的,非常高效的代码也可以写出来。如果你能更好地解释你的问题并给出圆顶代码来重新生成数据框,我可能会很容易。