2016-05-10 7 views
-1

私は季節データを含むマルチインデックスデータフレームからリサンプリングしています。無作為の夏にランダムな春が続いてランダムな冬を再サンプリングしたいのですが、私が選択するシーズンを指定していますが、ランダムなシーズンに続いてランダムなシーズンをサンプリングする方法しかありません。に必要なことは、いくつかの季節を欠けているように、季節的なシーケンスを尊重しながらデータフレームからのサンプル

import pandas as pd 
import numpy as np 

dates = pd.date_range('20100101',periods=1825) 
df = pd.DataFrame(data=np.random.randint(0,100,(1825,2)), columns =list('AB')) 
df['date'] = dates 
df = df[['date','A', 'B']] 

#season function 
def get_season(row): 
    if row['date'].month >= 3 and row['date'].month <= 5: 
     return '2' 
    elif row['date'].month >= 6 and row['date'].month <= 8: 
     return '3' 
    elif row['date'].month >= 9 and row['date'].month <= 11: 
     return '4' 
    else: 
     return '1' 

#apply the season function to dataframe 
df['Season'] = df.apply(get_season, axis=1) 

#Year column for multi-index 
df['Year'] = df['date'].dt.year 

#season column for multi-index 
df = df.set_index(['Year', 'Season'], inplace=False) 

再インデックスを(:

をリサンプリングするから、マルチインデックスデータフレームを取る:私は、コードを説明するためにですので、ここで間違ったつもりだどこで見ることができません

years = df['date'].dt.year.unique() 

サンプル:から範囲を選択するには)私が欲しいもの

newindex = [(2010L, '1'), (2011L, '1'), (2011L, '3'), (2012L, '4'), (2013L, '2'), (2015L, '3')] 

df = df.loc[newindex] 

#recreate season and year 
df['Season'] = df.apply(get_season, axis=1) 
df['Year'] = df['date'].dt.year 

年変数を行いますこれは、データフレームおよびサンプルの季節がランダムに、しかし、私はそれがの順序を尊重し、ランダムにしてないことを選択しているように見えるSeason == '1' Season == '2' Season == '3' Season =='4'から選択することを選択したにも関わらず、出力

dfs = [] 
for i in range(100): 
    dfs.append(df.query("Year == %d and Season == '1'" %np.random.choice(years, 1))) 
    dfs.append(df.query("Year == %d and Season == '2'" %np.random.choice(years, 1))) 
    dfs.append(df.query("Year == %d and Season == '3'" %np.random.choice(years, 1))) 
    dfs.append(df.query("Year == %d and Season == '4'" %np.random.choice(years, 1))) 

rnd = pd.concat(dfs) 

:データフレームから冬、春、夏、秋(1,2,3,4)。私はreplace == Trueを追加しようとしましたが、これは効果がありません。

これを調整してランダムな冬を選択し、次にランダムな春、ランダムな夏、次にランダムな秋を選択するにはどうすればよいですか?

おかげ

EDIT 1:

それが唯一のシーズンを選択していない年ができますので、コードを変更する - 私は1つだけを選択する指定てるにもかかわらず(それは、今以上の冬を選択)

dfs = [] 
for i in range(100): 
    dfs.append(df.query("Season == '1'" %np.random.choice(years, 1))) 
    dfs.append(df.query("Season == '2'" %np.random.choice(years, 1))) 
    dfs.append(df.query("Season == '3'" %np.random.choice(years, 1))) 
    dfs.append(df.query("Season == '4'" %np.random.choice(years, 1))) 

rnd = pd.concat(dfs) 
+1

以下の説明は、問題は、さまざまなデータフレームからのサンプリング、「異常な」季節の組み込みなど、より広範な問題に対する解決策を実際に探していることを示唆しています。より良い質問をし、役に立つ助言を得る方法をここで見てください:http://stackoverflow.com/help/how-to-ask – Stefan

答えて

1

あなたはあなたの季節、季節ごとの.sample()を生成するためにTimeGrouper('Q-Nov').groupby()を使用することができ、新しいindex EAのための設定CHシーズンのサンプルと、その後.sortlevel()に応じて:

はあなたのサンプルdfから始めますが、DateTimeIndex設定:

dates = pd.date_range('20100101', periods=1825) 
df = pd.DataFrame(data=np.random.randint(0, 100, (1825, 2)), columns=list('AB'), index=dates) 

DatetimeIndex: 1825 entries, 2010-01-01 to 2014-12-30 
Freq: D 
Data columns (total 2 columns): 
A 1825 non-null int64 
B 1825 non-null int64 

これは11月に四半期末をずらし、TimeGrouper()groupby()することができます(そして最後に、12月に値を割り当てますシリーズの最初のシーズンに再び)。.transform()を使用して元のdfseason_dictを経由して、翻訳、各グループのために.monthmax()を割り当て:

season_dict = {2: 1, 5: 2, 8: 3, 11: 4} 
df['season'] = df.groupby(pd.TimeGrouper('Q-Nov')).A.transform(lambda x: season_dict.get(x.index.month.max(), 1)) 

year列を作成し、indexseasonyearを設定します。

df['year'] = df.index.to_series().dt.year.astype(int) 
df = df.reset_index().set_index(['year', 'season']) 

からユニーク(year, season)の組み合わせを取得index

結果から

サンプル、あなたが後にソートすることができることを確認するために.reset_index()を使用して:あなたはseason全体を引っ張って、後でMultiIndexから選択することができるような形式に変換し

sample_seasons = sample_seasons.groupby('season').apply(lambda x: x.sample(frac=0.5).reset_index(drop=True)) 
sample_seasons = sample_seasons.reset_index(0, drop=True).sort_index() 

利回り
sample_seasons = list(sample_seasons.values) 
sample_seasons = [tuple(s) for s in sample_seasons] 

[(2011, 1), (2013, 2), (2011, 3), (2014, 4), (2014, 1), (2010, 2), (2010, 3), (2012, 4)] 

sample = df.loc[sample_seasons] 

    index A B 
year season     
2011 1  2011-01-01 33 64 
    1  2011-01-02 91 66 
    1  2011-01-03 37 47 
    1  2011-01-04 1 87 
    1  2011-01-05 68 47 
    1  2011-01-06 92 60 
    1  2011-01-07 81 7 
    1  2011-01-08 78 13 
    1  2011-01-09 31 67 
    1  2011-01-10 24 50 
    1  2011-01-11 71 55 
    1  2011-01-12 56 37 
    1  2011-01-13 25 87 
    1  2011-01-14 24 55 
    1  2011-01-15 29 97 
    1  2011-01-16 70 94 
    1  2011-01-17 18 37 
    1  2011-01-18 95 30 
    1  2011-01-19 58 87 
    1  2011-01-20 75 96 
    1  2011-01-21 52 63 
    1  2011-01-22 60 75 
    1  2011-01-23 39 58 
    1  2011-01-24 86 24 
    1  2011-01-25 61 21 
    1  2011-01-26 19 24 
    1  2011-01-27 5 71 
    1  2011-01-28 72 81 
    1  2011-01-29 0 45 
    1  2011-01-30 80 48 
...    ... .. .. 
2012 4  2012-11-01 90 44 
    4  2012-11-02 43 53 
    4  2012-11-03 3 49 
    4  2012-11-04 38 7 
    4  2012-11-05 64 44 
    4  2012-11-06 82 44 
    4  2012-11-07 38 75 
    4  2012-11-08 7 96 
    4  2012-11-09 52 9 
    4  2012-11-10 32 64 
    4  2012-11-11 30 38 
    4  2012-11-12 91 70 
    4  2012-11-13 63 18 
    4  2012-11-14 77 29 
    4  2012-11-15 58 51 
    4  2012-11-16 90 17 
    4  2012-11-17 87 85 
    4  2012-11-18 64 79 
    4  2012-11-19 10 61 
    4  2012-11-20 76 52 
    4  2012-11-21 9 40 
    4  2012-11-22 15 28 
    4  2012-11-23 14 33 
    4  2012-11-24 24 74 
    4  2012-11-25 38 43 
    4  2012-11-26 27 87 
    4  2012-11-27 6 30 
    4  2012-11-28 91 3 
    4  2012-11-29 32 64 
    4  2012-11-30 0 28 
+0

ありがとうございます - そして、より明確ではないことについて申し訳ありません - 私はランダムに各シーズンのサンプル日、私は同じシーズンを維持したい(例えば、01-12-2011から28-02-2012は冬であり、冬のように保つべきである)。したがって、新しいデータフレームは、データフレームから1つのランダムな冬をとり、その後にランダムな春、夏、秋が続きます。これらの季節はすべて、観測のサンプルではなく完全な観測です。 – Pad

+1

更新された回答を参照してください。 – Stefan

+0

もう一度感謝します - しかし、私がこれを行うと、すべての冬、すべての春、すべての夏、そしてすべての秋が選択されます。ランダムな冬、無作為の春、無作為の夏、ランダムな秋(完全な1年)などのシーケンスをx年分探しています。あなたの答えは助けますが、それは私が元々持っていたものに非常に似た何かをしています。これは私が作業しているコードの簡略化されたバージョンで、季節のない複数のマルチインデックスデータフレームから選択するので、ランダムな春を選択してランダム夏を選択する必要があります。これが意味をなさないことを願っています... – Pad

関連する問題