Skip to main content
 首页 » 编程设计

python之按周分组一个 Dataframe

2025年01月19日9powertoolsteam

我有一个数据框:

Date        Articles 
2010-01-04  ((though, reliant, advertis, revenu, internet,... 
2010-01-05  ((googl, expect, nexus, one, rival, iphon, hel... 
2010-01-06  ((while, googl, introduc, first, piec, hardwar... 
2010-01-07  ((googl, form, energi, subsidiari, appli, gove... 
2010-01-08  ((david, pogu, review, googl, new, offer, nexu... 
2010-01-12  ((the, compani, agre, hand, list, book, scan, ... 

Date 是索引,而 Articles 是元组的元组。

我有另一个数据框:

Date        Price 
2010-01-08  602.020 
2010-01-15  580.000 
2010-01-22  550.010 
2010-01-29  529.944 

其中 Date 也是索引,但按周划分。

我的问题是,我想在第二个数据框中创建另一列,其中包含截至该特定周的所有文章,由索引指示。就像我的第二个数据框中的第一行一样,我想要所有文章,从 2010 年 1 月 8 日之前的第一个数据框中进行组合(这样这将是我的第一个数据框中的前 4 个条目)。与 2010-01-15 一样,我需要从 2010-01-08 到 2010-01-14 的所有文章,依此类推。

如有任何帮助,我们将不胜感激。谢谢。

请您参考如下方法:

我们可以利用IntervalIndex.from_breaks和 pd.cut

df1 = pd.DataFrame({'Articles':  
                   {pd.Timestamp('2010-01-04 00:00:00'): [0, 1], 
                    pd.Timestamp('2010-01-05 00:00:00'): [2, 3], 
                    pd.Timestamp('2010-01-06 00:00:00'): [4, 5], 
                    pd.Timestamp('2010-01-07 00:00:00'): [6, 7], 
                    pd.Timestamp('2010-01-08 00:00:00'): [8, 9], 
                    pd.Timestamp('2010-01-12 00:00:00'): [10, 11]}}) 
 
            Articles 
2010-01-04  [0, 1] 
2010-01-05  [2, 3] 
2010-01-06  [4, 5] 
2010-01-07  [6, 7] 
2010-01-08  [8, 9] 
2010-01-12  [10, 11] 
 
mybins = pd.IntervalIndex.from_breaks( 
             pd.date_range("2010-1-1", periods=5, freq="7D"), 
             closed="left" 
         ) 
 
df1["bin"] = pd.cut(df1.index, bins=mybins) 
df1.groupby("bin")["Articles"].sum() 
 
bin 
[2010-01-01, 2010-01-08)    [0, 1, 2, 3, 4, 5, 6, 7] 
[2010-01-08, 2010-01-15)              [8, 9, 10, 11] 
[2010-01-15, 2010-01-22)                        None 
[2010-01-22, 2010-01-29)                        None 
Name: Articles, dtype: object