从每月到每天重新采样数据帧

时间:2020-06-01 15:47:54

标签: python pandas time-series resampling

这是我的问题:

这是我的DataFrame的示例(实际上是从2002年到2012年)

  icon.circle.strokeWidth = 0;
  icon.image.properties.width = "100%";
  icon.image.properties.height = "100%";
  icon.image.properties.maxWidth = "100%";
  icon.image.properties.maxHeight = "100%";

哪个给这个

df = pd.DataFrame(
    {'Date':["2002-07-31","2002-07-31","2002-07-31","2002-07-31","2002-07-31","2002-08-31","2002-08-31","2002-08-31","2002-08-31","2002-08-31",'2002-09-30','2002-09-30','2002-09-30','2002-09-30','2002-09-30'],
     'Name': ["Paul", "John", "Silvia", "Mike", "Cindy","Paul", "David", "Harry", "Mike", "Britney","Francis", "Michael", "Charlie", "Joe", "Hilary"]})

,我想通过从2002-07-31到2002-08-30以及从2002-08-31到2002-09-30保留所有名称的固定,对从每月到每日DataFrame的系列进行重新采样(更改仅发生在每个月的月底,因此看起来就像使用ffill()方法进行重新采样)。

我正在寻找的结果是这样的:

       Date     Name
0   2002-07-31  Paul
1   2002-07-31  John
2   2002-07-31  Silvia
3   2002-07-31  Mike
4   2002-07-31  Cindy
5   2002-08-31  Paul
6   2002-08-31  David
7   2002-08-31  Harry
8   2002-08-31  Mike
9   2002-08-31  Britney
10  2002-09-30  Francis
11  2002-09-30  Michael
12  2002-09-30  Charlie
13  2002-09-30  Joe
14  2002-09-30  Hilary

如您所见,名称仅在每个月底更改。 对我而言,最困难的步骤是我选择了5个名称,但我真的不知道如何重新采样到每日数据框,而每天仍然有5个名称。

我已经查看了此链接

Resampling Error : cannot reindex a non-unique index with a method or limit

但这不是一个真正的问题,我仍然没有找到任何解决方案来管理我的问题。 如果您有任何想法,欢迎您!

2 个答案:

答案 0 :(得分:2)

首先,确保您的Date列是datetime对象:

df['Date'] = df.Date.astype('datetime64')

然后,按Date列分组,按天将名称汇总到listresample并填写,最后执行explode展开{{1} }个名称:

list

答案 1 :(得分:1)

我将透视数据并使用ng run test对数据进行采样,然后堆叠:

asfreq

输出:

(df.assign(group=df.groupby('Date').cumcount())
  .set_index(['Date','group'])['Name']
  .unstack()
  .asfreq('D').ffill()
  .unstack()
  .reset_index('group',drop=True)
  .reset_index(name='Name')
)