python - 填写日期并使用以前的值

标签 python pandas

我的 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/

相关文章:

python - 使用 fillna 后如何更新数据框以进行排序?

python - Pandas 正则表达式返回包含 U 或 UN 和数字的任何字符串

python - Pandas 数据框列减法,处理 NaN

python - 如何创建这个嵌套的Python字典?

python - 显示 LIME 解释结果时是否可以使用 output_file 而不是 show_in_notebook?

python : group by columns with columns values that are grouped by occurs only once and retain all other columns

python - 在 Pandas Python 中组合两个数据框

python - 为什么比较两个数据帧时会得到不同的结果?

python - 查找最近 30 分钟内 DataFrame 中的元素数

python - 多索引 DataFrame - 利用其他行添加一行