python-如何计算每年每月的交易次数

问题描述 投票:0回答:1

上一个:https://stackoverflow.com/posts/61835927/

我有数据记录如下

category    dt          userid  amt
1           4/14/2019       1   140
1           5/1/2019        1   500
2           5/5/2019        1   300 
3           5/19/2019       1   230
2           6/17/2019       1   200
4           6/18/2019       1   400
1           7/30/2019       1   400
1           8/17/2019       1   300
2           12/2/2019       1   200
2           12/23/2019      1   500
1           1/10/2019       2   470
1           2/25/2019       2   450
2           10/4/2019       2   350

Q1:如果每月交易有=是,没有=否,我如何计算每月交易次数>

user    month1  month2  month3  month4  month5  month6  month7  month8  month9  month10 month11 month12 total_transaction_month
1       No      No      No      Yes     Yes     Yes     Yes     Yes     No      No      No      Yes      6
2       Yes     Yes     No      No      No      No      No      No      No      Yes     No      No       3

第二季度:如何对每个类别的交易进行计数

user   pro_cat1   pro_cat2  pro_cat3  pro_cat4    total_transaction_category
1      Yes        Yes       Yes       Yes         4
2      Yes        Yes       No        No          2

上一个:https://stackoverflow.com/posts/61835927/我有类似这样的数据记录dt userid amt 1 4/14/2019 1 140 1 5/1/2019 1 500 2 ...

python pandas dataframe
1个回答
0
投票

以下是我的答案,您可以使用groupby进行计算。希望这会有所帮助。

df['dt'] = pd.to_datetime(df.dt, format='%m/%d/%Y')

df['Month'] = df['dt'].dt.month
df.head()

df.groupby(['userid','Month']).sum()
df.groupby(['userid','category']).count()['amt']

© www.soinside.com 2019 - 2024. All rights reserved.