我試圖根據觀測到的天氣數據創建季節性數據的新序列。使用熊貓選擇特定序列中的時間序列數據
我想從這個數據框中提取季節,並創建一個新的數據幀,它具有按照時間順序依次相互排列的季節的隨機序列,例如,一個隨機的春天隨後是隨機的夏天,然後是隨機的秋天,隨後是隨機的冬天。以CSV格式
時間序列數據我的工作是提供here
到目前爲止是如下,我使用的代碼...
df = pd.read_csv("location of file")
#convert date column to datetime for querying
df['date'] = pd.to_datetime(df['date'], format= '%d-%b-%y')
#function which extracts seasons
def get_season(row):
if row['date'].month >= 3 and row['date'].month <= 5:
return 'spring'
elif row['date'].month >= 6 and row['date'].month <= 8:
return 'summer'
elif row['date'].month >= 9 and row['date'].month <= 11:
return 'autumn'
else:
return 'winter'
#apply the season function to the data frame
df['Season'] = df.apply(get_season, axis=1)
#Split into seasons
Sp = df.query('Season == "spring"')
#all the winters
W = df.query('Season == "winter"')
#all the summers
SU = df.query('Season == "summer"')
#all the autumns
Au = df.query('Season == "autumn"')
這裏的地方我不能讓我的頭在下一步做什麼。
這樣做是分開了所有季節,但不是每個單獨的季節(例如2006年冬季,2007年冬季等)。
我目前正在隨機序列的每個賽季,像這樣:
#sampling a random 92 days from winter
rows = np.random.choice(Sp.index.values, 92)
sampled_df = Sp.ix[rows]
但這不是我想要的東西,因爲它是採取隨機天從整個冬天塊,我想採取隨機賽季( 12月,1月,2月)。
爲了讓我生成這個新的序列,我需要根據每年的每個季節創建一個新的數據框,其中包含多列,所有列都以隨機彈簧開始,之後是隨機夏季,然後是隨機秋天,那麼隨機的冬天,幾百年的未來。
我不明白這是如何完成的。請幫忙!
感謝
非常感謝,現在想弄清楚如何去年12月! – Pad
我有一個想法:'df.loc [df ['date']。dt.month == 12,'Year'] + = 1'。但是要小心:2007年的冬天只包括1月和2月:) – IanS