3

2 つの日時の間のアクティビティをカウントできるようにするための一種のフォローアップの質問として、ここで非常によく答えられています: Create a Pandas dataframe with counts of items spanning a date range

残りの問題は、2 つのテーブルを合計して減算した後、最終月 ['END_DATE'] がゼロを表示することです。これは、すべての項目の終了日がその月またはそれ以前であるため、数学的には正しいのですが、この場合はそれらはその月に少なくともある程度はアクティブでした。END_DATE に 1 か月を追加する方が正しいので、最終月にアクティブであると表示されます (H2 はデータフレームです)。

コードは次のとおりです。

ends = H2['END_DATE'].apply(lambda t: t.to_period(freq='m')).value_counts()

たとえば、ロールフォワードと DateOffset(month=1) を使用しようとしました。日付オフセットの場合:

ends = (H2['END_DATE'].DateOffset(months=1)).apply(lambda t: t.to_period(freq='m')).value_counts()

これは私にこのエラーを与えます:

AttributeError: 'Series' object has no attribute 'DateOffset'
4

1 に答える 1

4

最も簡単な方法は、PeriodIndex に 1 (月) を追加することです。

In [21]: ends
Out[21]:
2000-05    1
2000-09    1
2001-06    1
Freq: M, dtype: int64

In [22]: ends.index = ends.index + 1

In [23]: ends
Out[23]:
2000-06    1
2000-10    1
2001-07    1
Freq: M, dtype: int64

私の最初の提案は、インデックスを再作成した後にシフトを行うことでした(とにかくそうしようとしているからです):

In [11]: ends
Out[11]:
2000-05    1
2000-09    1
2001-06    1
Freq: M, dtype: int64

In [12]: p = pd.PeriodIndex(freq='m', start='2000-1', periods=19)  # Note: needs to be one more than before

In [13]: sparse_ends = ends.reindex(p)

In [14]: sparse_ends.shift(1)
Out[14]:
2000-01   NaN
2000-02   NaN
2000-03   NaN
2000-04   NaN
2000-05   NaN
2000-06     1
2000-07   NaN
2000-08   NaN
2000-09   NaN
2000-10     1
2000-11   NaN
2000-12   NaN
2001-01   NaN
2001-02   NaN
2001-03   NaN
2001-04   NaN
2001-05   NaN
2001-06   NaN
2001-07     1
Freq: M, dtype: float64
于 2013-09-21T18:32:39.657 に答える