过去12个月在Pandas群比中的唯一值

2024-10-03 09:21:04 发布

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

如何在groupby中滚动12米并返回每行的唯一值(最好是列表中的值)

目前,我有一个熊猫数据框,如下所示。我希望按itemId对它们进行分组,并在过去12个月内(基于生效日期)将sellerId替换为唯一sellerId的列表。生效日期为月份格式。基本上,我想看看每个月的每个itemId,谁是过去12个月窗口内唯一的SellerId

            itemId   sellerId   effectiveDate
    1975245 2585893  31280      2005-12-31
    1975246 2585893  31280      2006-02-28
    1975247 2585893  5407       2006-06-30
    1975248 2585893  5407       2006-08-31
    1975249 2585893  5407       2006-09-30
    1975250 2585893  5407       2006-11-30
    1975254 2585893  5407       2007-05-31
    1975257 2585893  5407       2007-06-30
    1975258 2585893  5407       2007-07-31
    1975259 2585893  5407       2008-03-31
    ...

我想把它变成如下的东西:

            itemId  uniqueSellerIds effectiveDate
    1975245 2585893 [31280]         2005-12-31
    1975246 2585893 [31280]         2006-02-28
    1975247 2585893 [5407,31280]    2006-06-30
    1975248 2585893 [5407,31280]    2006-08-31
    ...

我尝试过使用groupby和rolling方法,但没有成功。谢谢你的帮助


Tags: 数据方法列表格式groupbyrolling月份itemid
2条回答

我将原始数据帧修改为:

    itemId          sellerId   effectiveDate
    19752572585893  31280      2005-12-31
    19752572585893  31280      2006-02-28
    19752592585894  31280      2008-01-31
    19752592585894  5407       2007-07-31
    19752592585894  5407       2008-03-31
    19752592585894  5407       2008-01-31

从那里我筛选出每个itemId的最近一年:

df['effectiveDate'] = pd.to_datetime(df['effectiveDate'])
filtered = df[df.groupby(by=['itemId']).apply(lambda g: 
                                              g['effectiveDate'] >= 
                                              g['effectiveDate'].max() - 
                                              pd.Timedelta(days=365)).values]                                                            

然后我将sellerId组合成如下:

filtered.groupby(by=['itemId'])['sellerId'].agg(lambda x: x.unique().tolist())     

剩下的就是获取最长日期,并将其连接回筛选和组合的数据:

max_dates = filtered.groupby(by=['itemId'])['effectiveDate'].max()
modified_df = pd.concat([compressed,max_dates],axis=1)  

结果:

                     sellerId effectiveDate
itemId                                     
19752572585893        [31280]    2006-02-28
19752592585894  [31280, 5407]    2008-03-31

使用dt.year怎么样

new_df = df.groupby([df["effectiveDate"].dt.year, df["itemId"]])["sellerId"].agg(list).to_frame()

print(new_df)
                                    sellerId
effectiveDate     itemId                      
2005              1975245 2585893  [31280]
2006              1975246 2585893  [31280]
                  1975247 2585893   [5407]
                  1975248 2585893   [5407]
                  1975249 2585893   [5407]
                  1975250 2585893   [5407]
2007              1975254 2585893   [5407]
                  1975257 2585893   [5407]
                  1975258 2585893   [5407]
2008              1975259 2585893   [5407]

相关问题 更多 >