如何使用 asfreq() 函数处理重复项。还有其他方法可以做到这一点吗?

问题描述 投票:0回答:1

我有一些来自不同国家不同来源的每小时发电数据。我从ENTSO-E透明平台网站下载数据,发现数据不一致的问题。对于某些数据集,时间序列中断了几个小时,因为源页面上没有适合该数据集的行 - 原因较少解释。我使用 asfreq() 方法解决了这个问题,该方法基本上用破折号填充了适当的空白,一切正常:)。例如,这解决了由于夏令时 (DST) 而减少一小时的问题,以及在 3 月最后一个星期日每小时 02:00:00 输入破折号的问题。

但是,当我想保留 10 月最后一个星期日的额外时间 02:00:00(给定)时,问题就出现了。 asfreq() 函数无法处理重复项,因此被迫使用 drop_duplicates。因此,我在 10 月份删除了这一额外的小时,但我无法做到这一点,因为我将整个年度系列缩短了这一行,并且如果我想使用其他数据进行更广泛的分析,我的生成集会更短并且不会将适当的时间与其他数据集进行映射,例如.能源价格或能源需求。

让我介绍一下这个问题的示例 DataFrame:

# Generate a datetime index with hourly frequency over a day
date_rng = pd.date_range(start='2024-01-01', end='2024-01-02', freq='H')

# Sample DataFrame
df = pd.DataFrame(date_rng, columns=['date'])
df['data'] = np.random.randn(len(df['date']))  # Random data
df.set_index('date', inplace=True)
# Intentionally removal of couple rows to meet DST March 2AM requirement
df = df.drop(pd.to_datetime(['2024-01-01 03:00', '2024-01-01 07:00', '2024-01-01 11:00']))

# Introduce a duplicate intentionally to meet DST October 2AM
duplicate_row = df.iloc[5]
part_before = df.iloc[:6]  # Include the original row in the first part
part_after = df.iloc[6:]  # Start the second part right after the original row

# Concatenate the three parts: before the original, the duplicate, and after the original
df = pd.concat([part_before, duplicate_row.to_frame().T, part_after]).reset_index()

df.rename(columns={'index':'date'},inplace=True)
df.set_index('date', inplace=True)

我的这个数据框的输出是这样的:

日期 数据
2024-01-01 00:00:00 0.958687
2024-01-01 01:00:00 -0.598715
2024-01-01 02:00:00 2.555558
2024-01-01 04:00:00 1.115459
2024-01-01 05:00:00 -1.719786
2024-01-01 06:00:00 -0.128536
2024-01-01 06:00:00 -0.128536
2024-01-01 08:00:00 -1.183776

“日期”列是一个索引。我想在此数据集中做的是在时间序列的间隙中插入连字符,但将此 06:00:00 行保留为重复行。

我想在此数据集中做的是在时间序列的间隙中插入破折号,但将此 06:00:00 行保留为副本,该行对应于 10 月的凌晨 2 点。我想要的数据框会像这样:

日期 数据
2024-01-01 00:00:00 0.958687
2024-01-01 01:00:00 -0.598715
2024-01-01 02:00:00 2.555558
2024-01-01 03:00:00 -
2024-01-01 04:00:00 1.115459
2024-01-01 05:00:00 -1.719786
2024-01-01 06:00:00 -0.128536
2024-01-01 06:00:00 -0.128536 #重复
2024-01-01 07:00:00 -
2024-01-01 08:00:00 -1.183776
python pandas dataframe date time-series
1个回答
0
投票

查找第一个和最后一个重复项:

d1 = df.drop_duplicates(subset=['index'], keep='first')
d2 = df.drop_duplicates(subset=['index'], keep='last')

根据需要修改最后一个值,并且

pd.concat([d1,d2])
© www.soinside.com 2019 - 2024. All rights reserved.