python - 用 pandas 填充信号时保留原始数据点

标签 python pandas

考虑以下测试数据集:

testdf = pandas.DataFrame({'t': [datetime(2015, 1, 1, 10,  0),
                                 datetime(2015, 1, 1, 11, 32),
                                 datetime(2015, 1, 1, 12,  0)],
                           'val': [1, 2, 3]})

我想使用简单的填充来插入此数据集,这样我至少每 30 分钟就有一个数据点,同时保留原始数据点。

合适的结果如下所示:

't'                'val'
2015-01-01 10:00   1
2015-01-01 10:30   1
2015-01-01 11:00   1
2015-01-01 11:30   1
2015-01-01 11:32   2
2015-01-01 12:00   3

哪个是实现此结果的好方法,最好使用标准 pandas 方法?

我知道 DataFrame.resample 方法,但是

a) 我似乎找不到 how 参数的正确值来实现所需的简单填充,并且

b)我找不到在结果中保留原始数据点的方法。

问题 b) 当然可以通过手动将原始数据点添加到重新采样的 DataFrame 中来规避,尽管我不认为这是一个特别简洁的解决方案。

最佳答案

生成具有缺失时间戳的索引,并创建具有 NaN 值的数据帧。然后将其与 combine_first 方法结合并填写 NaN 值:

idx = pandas.date_range(datetime(2015, 1, 1, 10, 0), datetime(2015, 1, 1, 12, 0), freq='30min')
df = pandas.DataFrame(numpy.nan, index=idx, columns=['val'])

testdf.set_index('t', inplace=True)
testdf.combine_first(df).fillna(method='ffill')

documentation of the combine_first method内容如下:

Combine two DataFrame objects and default to non-null values in frame calling the method. Result index columns will be the union of the respective indexes and columns

fillna 方法的 ffill 方法执行以下操作 ( source ):

ffill: propagate last valid observation forward to next valid backfill

关于python - 用 pandas 填充信号时保留原始数据点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35918248/

相关文章:

python - 如何从调用方法的函数中修补参数?

python - 使用Pandas dataframe处理列表数据get loc错误

python - 尝试从 python 字典创建一个二维数组

python - 如何摆脱从 CSV 文件读取的 pandas DataFrame 中的 "Unnamed: 0"列?

python - pandas datetime 将星期日设置为一周的第一天

python - 根据匹配对不同工作表/文件中的值求和

python-3.x - 手动排序多索引级别

python - 使用数组结构将 DataFrame 上传到 BigQuery

api - 如何将 pandas.DataFrame 转换为 gviz_api.DataTable

python - 如何在 python 中获取 xgb.train 的超参数