我一直在研究这个问题,并且非常接近。本质上,我想从事件数据库中按类型创建事件计数的时间序列。我真的很亲近。这是我到目前为止所做的:
从我的数据框的缩写版本开始:
event_date year time_precision event_type \
0 2020-10-24 2020 1 Battles
1 2020-10-24 2020 1 Riots
2 2020-10-24 2020 1 Riots
3 2020-10-24 2020 1 Battles
4 2020-10-24 2020 2 Battles
我希望时间序列按月和年,所以首先我将日期转换为datetime
:
nga_df.event_date = pd.to_datetime(nga_df.event_date)
然后,我想按类型创建事件的时间序列,所以我对它们进行一次性编码:
nga_df = pd.get_dummies(nga_df, columns=['event_type'], prefix='', prefix_sep='')
接下来,我需要提取月份,以便创建每月计数:
nga_df['month'] = nga_df.event_date.apply(lambda x: x.month)
最后,我离这里很近,我按月和年对数据进行分组并进行转置:
conflict_series = nga_df.groupby(['year','month']).sum()
conflict_series.T
这导致了这个可爱的新数据框:
year 1997 ... 2020
month 1 2 3 4 5 6 ... 5 6 7
fatalities 11 30 38 112 17 29 ... 1322 1015 619
Battles 4 4 5 13 2 2 ... 77 99 74
Explosions/Remote violence 2 1 0 0 3 0 ... 38 28 17
Protests 1 0 0 1 0 1 ... 31 83 50
Riots 3 3 4 1 4 1 ... 27 14 18
Strategic developments 1 0 0 0 0 0 ... 7 2 7
Violence against civilians 3 5 7 3 2 1 ... 135 112 88
所以,我想我需要做的是组合我的索引(转置后的列),使它们成为一个索引。我该怎么做呢?
最终目标是将这些数据与经济指标结合起来,看看是否有趋势,所以我需要两个数据集采用相同的形式,其中列是不同值的月度计数。