[英]Create new dataframe from multiple multi-index dataframes
我想創建一個x年的新數據框,該數據框需要使用以前天氣數據中的隨機季節。
代碼來說明問題:
import pandas as pd
import numpy as np
dates = pd.date_range('20070101',periods=3200)
df = pd.DataFrame(data=np.random.randint(0,100,(3200,1)), columns =list('A'))
df['date'] = dates
df = df[['date','A']]
將季節函數應用於日期時間索引
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'
應用功能
df['Season'] = df.apply(get_season, axis=1)
創建“年份”列以建立索引
df['Year'] = df['date'].dt.year
年份和季節的多指標
df = df.set_index(['Year', 'Season'], inplace=False)
根據季節創建新的數據框以從中選擇
winters = df.query('Season == "1"')
springs = df.query('Season == "2"')
summers = df.query('Season == "3"')
autumns = df.query('Season == "4"')
我現在想創建一個新的DataFrame
這需要從一個隨機的冬天winters
據幀,然后從隨機彈簧springs
,其次是從隨機夏天summers
從隨機秋季autumns
及這是否為指定的年數(如100),但我看不到該怎么做。
編輯:
允許重復的季節(應該隨機采樣季節),並且第一個春天不必與第一個冬天屬於同一年,這無關緊要。
編輯2:使用所有季節性數據框的解決方案:
years = df['date'].dt.year.unique()
dfs = []
for i in range(outputyears):
dfs.append(winters.query("Year == %d" %np.random.choice(years, 1)))
dfs.append(springs.query("Year == %d" %np.random.choice(years, 1)))
dfs.append(summers.query("Year == %d" %np.random.choice(years, 1)))
dfs.append(autumns.query("Year == %d" %np.random.choice(years, 1)))
rnd = pd.concat(dfs)
這很可能不是最好的方法,但是您可以這樣操作:
years = df['date'].dt.year.unique()
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.