在连续事务中对重复项进行计数

2024-04-19 12:43:00 发布

您现在位置:Python中文网/ 问答频道 /正文

使用此数据帧:

Customer_ID | transaction_nr | item_ID
ABC            1                6438097
ABC            2                9703489
ABC            2                6438097
BCD            1                0093753
BCD            2                9084378
BCD            3                9084378

我要计算事务1和事务2中具有相同项目标识的客户标识的不同计数。另外,我要计算事务2和事务3中具有相同项目的客户ID的不同计数。你知道吗

我怎么能不用手动旋转和数数呢?你知道吗


Tags: 数据项目id客户customer手动item事务
3条回答

通过使用crosstab

pd.crosstab(df['Customer_ID'],df['transaction_nr'],df['item_ID'],aggfunc=len)
    Out[795]: 
    transaction_nr    1    2    3
    Customer_ID                  
    ABC             1.0  2.0  NaN
    BCD             1.0  1.0  1.0

这是支票和身份证

pd.crosstab(df['Customer_ID'],df['item_ID'],df['transaction_nr'].isin([1,2]),aggfunc=sum)
Out[798]: 
item_ID      93753    6438097  9084378  9703489
Customer_ID                                    
ABC              NaN      2.0      NaN      1.0
BCD              1.0      NaN      1.0      NaN

只需调用^{}并传递^{}

In [212]:
df = pd.DataFrame(np.random.randint(0, 2, (10, 4)), columns=list('abcd'))
df.apply(pd.Series.value_counts)

Out[212]:
   a  b  c  d
0  4  6  4  3
1  6  4  6  7

您可以使用groupby应用程序:

In [11]: df.groupby(["Customer_ID", "item_ID"]).apply(lambda x: x["transaction_nr"].isin([1, 2]).sum() == 2)
Out[11]:
Customer_ID  item_ID
ABC          6438097     True
             9703489    False
BCD          93753      False
             9084378    False
dtype: bool

In [12]: df.groupby(["Customer_ID", "item_ID"]).apply(lambda x: x["transaction_nr"].isin([2, 3]).sum() == 2)
Out[12]:
Customer_ID  item_ID
ABC          6438097    False
             9703489    False
BCD          93753      False
             9084378     True
dtype: bool

# To get the count:
In [13]: df.groupby(["Customer_ID", "item_ID"]).apply(lambda x: x["transaction_nr"].isin([2, 3]).sum() == 2).sum()
Out[12]: 1

在这里,应用:

.apply(lambda x: x["transaction_nr"].isin([1, 2]).sum() == 2)

检查是否同时存在事务1和事务2(如果存在,则总和为2),以及事务2和事务3。你知道吗

注意:您可能必须首先.drop_duplicates,这取决于您的数据集中是否保证了这一点。

相关问题 更多 >