在给定日期对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
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
。很高兴我能帮助=)快乐编码!