我试图根据观测到的天气数据创建季节性数据的新序列。使用熊猫选择特定序列中的时间序列数据
我想从这个数据框中提取季节,并创建一个新的数据帧,它具有按照时间顺序依次相互排列的季节的随机序列,例如,一个随机的春天随后是随机的夏天,然后是随机的秋天,随后是随机的冬天。以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