[英]Extract multi-year three month series (winter) from pandas dataframe
我有一個熊貓數據框架,其中包含70年的每小時數據,看起來像這樣:
pressure
2015-06-01 18:00:00 945.6
2015-06-01 19:00:00 945.6
2015-06-01 20:00:00 945.4
2015-06-01 21:00:00 945.4
2015-06-01 22:00:00 945.3
我想從每年中提取冬季(DJF),並生成一個帶有一系列冬季的新DataFrame。 我發現了很多復雜的東西(例如,將df.index.month
提取為新列,然后再處理此列),但是有沒有辦法使冬天的月份變得簡單呢?
您可以使用map()
:
import pandas as pd
df = pd.DataFrame({'date' : [datetime.date(2015, 11, 1), datetime.date(2015, 12, 1), datetime.date(2015, 1, 1), datetime.date(2015, 2, 1)],
'pressure': [1,2,3,4]})
winter_months = [12, 1, 2]
print df
# date pressure
# 0 2015-11-01 1
# 1 2015-12-01 2
# 2 2015-01-01 3
# 3 2015-02-01 4
df = df[df["date"].map(lambda t: t.month in winter_months)]
print df
# date pressure
# 1 2015-12-01 2
# 2 2015-01-01 3
# 3 2015-02-01 4
編輯:我注意到,在您的示例中,日期是數據框的索引。 這仍然有效:
df = df[df.index.map(lambda t: t.month in winter_months)]
我才發現
df[(df.index.month==12) | (df.index.month==1) | (df.index.month==2)]
工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.