假设我有以下数据框

bb = pd.DataFrame(data = {'date' :['','','','2015-09-02', '2015-09-02', '2015-09-03','','2015-09-08', '', '2015-09-11','2015-09-14','','' ]})
bb['date'] = pd.to_datetime(bb['date'], format="%Y-%m-%d")

我想线性插值和外插以填充缺失的日期值。我使用了以下代码,但它没有改变任何东西。我是 Pandas 的新手。请帮忙
bb= bb.interpolate(method='time')

最佳答案

要推断,您必须使用 bfill()ffill() 。缺失值将由后退(或前进)值分配。

要线性插值,您必须使用函数 interpolate 但日期需要转换为数字:

import numpy as np
import pandas as pd
from datetime import datetime

bb = pd.DataFrame(data = {'date' :['','','','2015-09-02', '2015-09-02', '2015-09-03','','2015-09-08', '', '2015-09-11','2015-09-14','','' ]})
bb['date'] = pd.to_datetime(bb['date'], format="%Y-%m-%d")

# convert to seconds
tmp = bb['date'].apply(lambda t: (t-datetime(1970,1,1)).total_seconds())
# linear interpolation
tmp.interpolate(inplace=True)
# back convert to dates
bb['date'] = pd.to_datetime(tmp, unit='s')
bb['date'] = bb['date'].apply(lambda t: t.date())
# extrapolation for the first missing values
bb.bfill(inplace='True')

print bb

结果:
         date
0  2015-09-02
1  2015-09-02
2  2015-09-02
3  2015-09-02
4  2015-09-02
5  2015-09-03
6  2015-09-05
7  2015-09-08
8  2015-09-09
9  2015-09-11
10 2015-09-14
11 2015-09-14
12 2015-09-14

关于python - 在python中插入/推断缺失的日期?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37783842/

10-14 04:21