私は可能な限りコードを簡略化しましたが、それはまだかなり長いので問題を説明する必要があります。パンダのデータフレームからループ内で繰り返しサンプリングする
私はデータフレームからの気象データをサンプリングしています:
import numpy as np
import pandas as pd
#dataframe
dates = pd.date_range('19510101',periods=16000)
data = pd.DataFrame(data=np.random.randint(0,100,(16000,1)), columns =list('A'))
data['date'] = dates
data = data[['date','A']]
#create year and season column
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'
data['Season'] = data.apply(get_season, axis=1)
data['Year'] = data['date'].dt.year
Iが所定の年/季節のタプルを使用してランダムな年を選択します:以下のように
#generate an index of year and season tuples
index = [(1951L, '1'),
(1951L, '2'),
(1952L, '4'),
(1954L, '3'),
(1955L, '1'),
(1955L, '2'),
(1956L, '3'),
(1960L, '4'),
(1961L, '3'),
(1962L, '2'),
(1962L, '3'),
(1979L, '2'),
(1979L, '3'),
(1980L, '4'),
(1983L, '2'),
(1984L, '2'),
(1984L, '4'),
(1985L, '3'),
(1986L, '1'),
(1986L, '2'),
(1986L, '3'),
(1987L, '4'),
(1991L, '1'),
(1992L, '4')]
これからのサンプル:
は、各シーズンの年のリストを4つ生成します(春用、夏用など)
coldsample = [[],[],[],[]] #empty list of lists
for (yr,se) in index:
coldsample[int(se)-1] += [yr] #function which gives the years which have extreme seasons [[1],[2],[3],[4]]
coldsample
は
cold_ctr = 0 #variable to count from (1 is winter, 2 spring, 3 summer, 4 autumn)
coldseq = [] #blank list
for yrlist in coldsample:
ran_yr = np.random.choice(yrlist, 1) #choose a randomly sampled year from previous cell
cold_ctr += 1 # increment cold_ctr variable by 1
coldseq += [(ran_yr[0], cold_ctr)] #populate coldseq with a random year and a random season (in order)
は、複数のランダム年
df = []
for i in range (5): #change the number here to change the number of output years
for item in coldseq: #item is a tuple with year and season, coldseq is cold year and season pairs
df.append(data.query("Year == %d and Season == '%d'" % item))
選択した新しいデータフレームを生成し、このリストからランダム年選択の問題は、これは同じ年を持っている(coldseq
から選択ということです/ season組み合わせ)、新しいcoldseqを生成しません。 coldseqを空にリセットして、最後のforループの繰り返しごとに新しいものを生成する必要がありますが、これを行う方法はわかりません。私は複数の方法でループ内にコードを埋め込もうとしましたが、うまくいかないようです。
申し訳ありませんが、これは私が探している何をしない、私は新しいを作成したいです季節系列(春、夏、秋、冬)を尊重するデータフレーム。 – Pad
ランダムなサンプルから新しいデータフレームを作成した後、新しいデータフレームを注文するだけで何が問題になりますか? –
申し訳ありませんが、これは必要な方法でシーケンスから選択しません - 私は解決策で投稿に答えました – Pad