我有一个包含 70 年每小时数据的 pandas DataFrame,如下所示:
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
我想从每年中提取冬季月份 (D-J-F) 并生成一个包含一系列冬季的新 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)]
关于python - 从 pandas 数据框中提取多年三个月系列(冬季),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30963917/