2016-12-21 14 views
0

私は数ヶ月にわたって実行されているデータを分析し、月に数字を生成して保存しています。これまでのところ、これは同じ暦年にあると効果的でしたが、データが次の年に渡ったときにループがどのように動作するかを示す方法がわかりません。プロダクションのためのカスタム日付(月年)から(月年+ N)までのパンダループ

例コード:彼らはパンダのdatetimeオブジェクトの代わりに、私が使用したdatetime.dateオブジェクトを使用していますが

import pandas as pd 
import datetime as datetime 
import matplotlib as plt 

df = pd.read_csv("file.csv") 
df.index = df.Datetime 

for month in range(4,12): #Data starts in April in this example 
    fig, axes = plt.subplots(nrows=2,ncols=1, sharex=True, figsize =(18,10)) 
    startDate = datetime.date(2016,month,1) 
    stopDate = datetime.date(2016,month+1,1) 
    date_val = startDate.strftime("%B %Y") 

    k=0 
    df.PRe[startDate:stopDate].plot(ax=axes[k]) 
    #ylim, xlim, title etc 
    k=1 
    df.PRp[startDate:stopDate].plot(ax=axes[k]) 

    plt.savefig("PRe and PRp in %s.png"%date_val,bbox_inches="tight") 

This SO questionが、近づきます。ソリューションに対応するためにコードを修正する必要がありますか? それ以外の場合は、既知の開始日と終了日のいずれか、または開始日と終了日のいずれかになると、2016を超えるとこれを動作させるためのパンダ/ピジョンソニックの方法がありますか?

答えて

1

あなたはdateoffsetを使用することができます。

month = 4 
startDate = datetime.date(2016,month,1) 
print (startDate) 
stopDate = (startDate + pd.offsets.MonthBegin()).date() 
print (stopDate) 
2016-04-01 
2016-05-01 

month = 4 
startDate = datetime.date(2016,month,1) 
print (startDate) 
stopDate = (startDate + pd.offsets.DateOffset(months=1)).date() 
print (stopDate) 
2016-04-01 
2016-05-01 

yearmonthによって選択が必要な場合は別の解決策はdatetimeindex partial string indexingです:

df.PRe['2016-4'].plot(ax=axes[k]) 

df.PRe[str(2016)+'-'+str(month)].plot(ax=axes[k]) 

ソリューションDatetimeIndex.to_periodによってユニークmonth期間によって独特の年と月によってdatetimeindexにおける必要性ループの場合:jezraelの答え質問を解決@

start = pd.to_datetime('2015-10-24') 
rng = pd.date_range(start, periods=10, freq='3W') 

df = pd.DataFrame({'PRe': np.random.randint(10, size=10)}, index=rng) 
print (df) 
      PRe 
2015-10-25 2 
2015-11-15 3 
2015-12-06 3 
2015-12-27 1 
2016-01-17 8 
2016-02-07 4 
2016-02-28 2 
2016-03-20 6 
2016-04-10 8 
2016-05-01 0 
2015-10-25 2 
for date in df.index.to_period('m').unique(): 
    print (df.PRe[str(date)]) 

Freq: 3W-SUN, Name: PRe, dtype: int32 
2015-11-15 3 
Freq: 3W-SUN, Name: PRe, dtype: int32 
2015-12-06 3 
2015-12-27 1 
Freq: 3W-SUN, Name: PRe, dtype: int32 
2016-01-17 8 
Freq: 3W-SUN, Name: PRe, dtype: int32 
2016-02-07 4 
2016-02-28 2 
Freq: 3W-SUN, Name: PRe, dtype: int32 
2016-03-20 6 
Freq: 3W-SUN, Name: PRe, dtype: int32 
2016-04-10 8 
Freq: 3W-SUN, Name: PRe, dtype: int32 
2016-05-01 0 
Freq: 3W-SUN, Name: PRe, dtype: int32 
0

。以下は後世の解決策です。

import pandas as pd 
import matplotlib as plt 

df = pd.read_csv("file.csv") 
df.index = df.Datetime 

startDate = df.index[0] #seed the while loop, format Timestamp 
while (startDate >= df.index[0]) & (startDate < df.index[-1]): 
    fig, axes = plt.subplots(nrows=2,ncols=1, sharex=True, figsize =(18,10)) 

    stopDate = (startDate + pd.offsets.MonthBegin())#stopDate also Timestamp 
    date_val = startDate.strftime("%B %Y")#Date as Month Year string 

    k=0 
    df.PRe[startDate:stopDate].plot(ax=axes[k]) 
    #ylim, xlim, title etc 
    k=1 
    df.PRp[startDate:stopDate].plot(ax=axes[k]) 
    #ylim, xlim, title etc 
    plt.savefig("PRe and PRp in %s.png"%date_val,bbox_inches="tight") 
    startDate = stopDate 
関連する問題