找到最大化数量的列组合
finding combination of columns which maximizes a quantity
我有一个如下所示的数据框:
cuid day transactions
0 a mon 1
1 a tue 2
2 b tue 2
3 b wed 1
对于每个 'cuid'(客户 ID),我想找到交易次数最多的那一天。例如对于上面的 df,输出应该是一个看起来像
的 df
cuid day transactions
1 a tue 2
2 b tue 2
我试过如下代码:
dd = {'cuid':['a','a','b','b'],'day':['mon','tue','tue','wed'],'transactions':[1,2,2,1]}
df = pd.DataFrame(dd)
dfg = df.groupby(by=['cuid']).agg(transactions=('transactions',max)).reset_index()
但我不知道如何加入 dfg
和 df
。
方法 1
idxmax
为您提供某个列值(此处为 transaction
)最大的索引。
首先我们设置索引,
step1 = df.set_index(['day', 'cuid'])
然后我们找到idxmax,
indices = step1.groupby('cuid')['transactions'].idxmax()
我们得到了结果
step1.loc[indices].reset_index()
方法2
df.groupby('cuid')\
.apply(lambda df: df[df['transactions']==df['transactions'].max()])\
.reset_index(drop=True)
我有一个如下所示的数据框:
cuid day transactions
0 a mon 1
1 a tue 2
2 b tue 2
3 b wed 1
对于每个 'cuid'(客户 ID),我想找到交易次数最多的那一天。例如对于上面的 df,输出应该是一个看起来像
的 df cuid day transactions
1 a tue 2
2 b tue 2
我试过如下代码:
dd = {'cuid':['a','a','b','b'],'day':['mon','tue','tue','wed'],'transactions':[1,2,2,1]}
df = pd.DataFrame(dd)
dfg = df.groupby(by=['cuid']).agg(transactions=('transactions',max)).reset_index()
但我不知道如何加入 dfg
和 df
。
方法 1
idxmax
为您提供某个列值(此处为 transaction
)最大的索引。
首先我们设置索引,
step1 = df.set_index(['day', 'cuid'])
然后我们找到idxmax,
indices = step1.groupby('cuid')['transactions'].idxmax()
我们得到了结果
step1.loc[indices].reset_index()
方法2
df.groupby('cuid')\
.apply(lambda df: df[df['transactions']==df['transactions'].max()])\
.reset_index(drop=True)