如何在python中计算一对多关系数据框架中的元素



我有一个数据框架,其中包含客户端代码,合同编号和合同中的产品。

像这样:

苏打苏打

IIUC,您想要每个client_code(或可能contract_number)的累积计数-您可以使用cumcount函数:

df.loc[:, 'count'] = df.groupby('client_code').cumcount() + 1 

client_code  contract_number product  count
0        AAAA             1000   Water      1
1        AAAA             1000    Soda      2
2        AAAA             1000    Food      3
3        BACD             1001   Water      1
4        BACD             1001    Soda      2
5        DAMR             1002    Food      1

最新更新