我的 pandas 数据框如下所示
country date gd
US 01-01-2014 2
US 01-01-2015 3
US 01-01-2013 0.4
UK 01-01-2000 0.7
UK 02-01-2001 0.5
UK 01-01-2016 1
我想做的是:
1) 从每个国家/地区的最短日期开始填写所有日期(每天),例如美国是 01-01-2013 到今天,英国是 01-01-2000 到今天。
2) 用以前的可用数据填充 gd 列
非常感谢你的帮助
最佳答案
In [67]: today = pd.to_datetime(pd.datetime.now()).normalize()
In [68]: l = df.country.nunique()
In [72]: df.append(pd.DataFrame({'country':df.country.unique(), 'date':[today]*l, 'gd':[np.nan]*l})) \
...: .sort_values('date') \
...: .groupby('country') \
...: .resample('1D', on='date') \
...: .mean() \
...: .reset_index() \
...: .ffill()
...:
Out[72]:
country date gd
0 UK 2000-01-01 0.7
1 UK 2000-01-02 0.7
2 UK 2000-01-03 0.7
3 UK 2000-01-04 0.7
4 UK 2000-01-05 0.7
5 UK 2000-01-06 0.7
6 UK 2000-01-07 0.7
7 UK 2000-01-08 0.7
8 UK 2000-01-09 0.7
9 UK 2000-01-10 0.7
... ... ... ...
8059 US 2017-07-09 3.0
8060 US 2017-07-10 3.0
8061 US 2017-07-11 3.0
8062 US 2017-07-12 3.0
8063 US 2017-07-13 3.0
8064 US 2017-07-14 3.0
8065 US 2017-07-15 3.0
8066 US 2017-07-16 3.0
8067 US 2017-07-17 3.0
8068 US 2017-07-18 3.0
[8069 rows x 3 columns]
关于python - 填写日期并使用以前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45176903/