gpt4 book ai didi

python - 按周分组一个 Dataframe

转载 作者:太空宇宙 更新时间:2023-11-04 04:46:00 25 4
gpt4 key购买 nike

我有一个数据框:

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_breakspd.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

关于python - 按周分组一个 Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49599923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com