繁体   English   中英

如何在 python 中数组的下一个元素的条件下过滤二维数组

[英]how to filter 2d array on the condition of the next element of the array in python

如何过滤二维数组并仅保留那些满足条件的元素,即如果有 2 次点击相继出现然后 tocart,则从第一次点击示例中过滤数组

df = pd.DataFrame({
  'a': ['Jason', 'Jason', 'Boby', 'Boby', 'Boby','Boby','Boby','Cob'],
  'b': [1, 2, 5, 5, 4,2,1, 6],
  'c': ['x', 'y', 'z', 'x', 'y','d', 'd','z'],
  'd': ['click', 'click', 'tocart', 'click', 'tocart','click','click', 'tocart']
})


df  = df.groupby(["a"]).apply(lambda x: x.sort_values(["b"], ascending = True)).reset_index(drop=True)


df['combine'] = df[['b','c','d']].values.tolist()

df = df[['a','combine']].groupby('a').agg(pd.Series.tolist).reset_index()
df

在鲍比的情况下

一个 结合
博比 [[1, d, click],[2, d, click], [4, y, tocart], [5, x, click],[5, z, tocart]]
棒子 [[6, z, tocart]]

我想失去从阵列 bc 的第一次单击,然后再单击一次,然后单击 tocart。 Cob 不应该出现在结果 df 中,因为他的数组中没有“点击”,而 Jason 的数组中没有点击。

我期望的结果

一个 结合
博比 [[2, d, click], [4, y, tocart], [5, x, click],[5, z, tocart]]

像这样的东西会起作用吗? 基本上或多或少地做了你描述的事情:

def slicing(y):
    x = y.iloc[:,1:].to_numpy()
    if x[:,-1].tolist()[-2:] == ['click', 'tocart']:
        return x[-2:]
    else:
        return np.nan
out = df.sort_values(by='b').groupby('a').apply(slicing).dropna()

Output:

a
Boby    [[5, z, click], [5, x, tocart]]
dtype: object

暂无
暂无

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

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