在给定日期对Python系列或数据帧重新采样

在给定日期对Python系列或数据帧重新采样,python,pandas,Python,Pandas,给定一个熊猫数据帧或序列,我想在特定时间点对其重新采样。 这可能意味着删除值或通过向前填充以前的值来添加新值 例子 给定由定义的系列X import pandas rng_X = pandas.to_datetime( ['2021-01-01', '2021-01-02', '2021-01-07', '2021-01-08', '2021-02-01']) X = pandas.Series([0, 2, 4, 6, 8], rng_X) X 2021-01-01 0 2021-01

给定一个熊猫数据帧或序列,我想在特定时间点对其重新采样。 这可能意味着删除值或通过向前填充以前的值来添加新值

例子 给定由定义的系列
X

import pandas
rng_X = pandas.to_datetime(
['2021-01-01', '2021-01-02', '2021-01-07', '2021-01-08', '2021-02-01'])
X = pandas.Series([0, 2, 4, 6, 8], rng_X)

X
2021-01-01    0
2021-01-02    2
2021-01-07    4
2021-01-08    6
2021-02-01    8
在日期重新采样
X

rng_Y = pandas.to_datetime(
['2021-01-02', '2021-01-03', '2021-01-07', '2021-01-08', '2021-01-09', '2021-01-10'])
预期产量为

2021-01-02    2
2021-01-03    2
2021-01-07    4
2021-01-08    6
2021-01-09    6
2021-01-10    6
  • 2021-01-01
    从输出中删除,因为它不在
    rng_y
  • 2021-01-03
    被添加到输出中,其值从
    2021-01-02
    向前复制,因为它不存在于
    X
  • 2021-01-09
    2021-01-10
    也被添加到输出中,其值是从
    2021-01-08
  • 2021-02-01
    从输出中删除,因为它不存在于
    rng_Y
尝试将方法设置为'ffill':

X = X.reindex(rng_Y, method='ffill')
X

2021-01-02    2
2021-01-03    2
2021-01-07    4
2021-01-08    6
2021-01-09    6
2021-01-10    6
dtype: int32

完整代码:

import pandas as pd

rng_X = pd.to_datetime(['2021-01-01', '2021-01-02', '2021-01-07', '2021-01-08',
                        '2021-02-01'])

rng_Y = pd.to_datetime(['2021-01-02', '2021-01-03', '2021-01-07', '2021-01-08',
                        '2021-01-09', '2021-01-10'])

X = pd.Series([0, 2, 4, 6, 8], rng_X)

X = X.reindex(rng_Y, method='ffill')
print(X)

如果
X
是数据帧(
df
),而不是序列:

df = pd.DataFrame([0, 2, 4, 6, 8], index=rng_X, columns=['X'])
df = df.reindex(rng_Y, method='ffill')
df

            X
2021-01-02  2
2021-01-03  2
2021-01-07  4
2021-01-08  6
2021-01-09  6
2021-01-10  6

非常感谢。我知道这应该很简单,但我就是找不到解决方案,因为我在搜索查询中使用了
resample
,而不是
reindex
。很高兴我能帮助=)快乐编码!