【发布时间】:2020-11-06 07:06:32
【问题描述】:
问题
我需要将 DataFrame 的长度减少到某个外部定义的整数(可以是两行、10,000 行等,但总是会减少总长度),但我也希望保留生成的 DataFrame 代表原来的。原始 DataFrame(我们称之为df)有一个datetime 列(utc_time)和一个数据值列(data_value)。日期时间始终是连续的、不重复的,尽管间隔不均匀(即,数据可能“丢失”)。对于本例中的 DataFrame,时间戳以十分钟为间隔(当数据存在时)。
尝试
为了做到这一点,我立即想到了用以下逻辑进行重采样:找出第一个时间戳和最后一个时间戳之间的秒差,将其除以所需的最终长度,这就是重采样因子。我在这里设置:
# Define the desired final length.
final_length = 2
# Define the first timestamp.
first_timestamp = df['utc_time'].min().timestamp()
# Define the last timestamp.
last_timestamp = df['utc_time'].max().timestamp()
# Define the difference in seconds between the first and last timestamps.
delta_t = last_timestamp - first_timestamp
# Define the resampling factor.
resampling_factor = np.ceil(delta_t / final_length)
# Set the index from the `utc_time` column so that we can resample nicely.
df.set_index('utc_time', drop=True, inplace=True)
# Do the resampling.
resamp = df.resample(f'{resampling_factor}S')
查看resamp,我只是循环打印:
for i in resamp:
print(i)
这产生了(在我方面进行了一些清理)以下内容:
utc_time data_value
2016-09-28 21:10:00 140.0
2016-09-28 21:20:00 250.0
2016-09-28 21:30:00 250.0
2016-09-28 21:40:00 240.0
2016-09-28 21:50:00 240.0
... ...
2018-08-06 13:00:00 240.0
2018-08-06 13:10:00 240.0
2018-08-06 13:20:00 240.0
2018-08-06 13:30:00 240.0
2018-08-06 13:40:00 230.0
[69889 rows x 1 columns])
utc_time data_value
2018-08-06 13:50:00 230.0
2018-08-06 14:00:00 230.0
2018-08-06 14:10:00 230.0
2018-08-06 14:20:00 230.0
2018-08-06 14:30:00 230.0
... ...
2020-06-14 02:50:00 280.0
2020-06-14 03:00:00 280.0
2020-06-14 03:10:00 280.0
2020-06-14 03:20:00 280.0
2020-06-14 03:30:00 280.0
[97571 rows x 1 columns])
utc_time data_value
2020-06-14 03:40:00 280.0
2020-06-14 03:50:00 280.0
2020-06-14 04:00:00 280.0
2020-06-14 04:10:00 280.0
2020-06-14 04:20:00 280.0
... ...
2020-06-15 00:10:00 280.0
2020-06-15 00:20:00 270.0
2020-06-15 00:30:00 270.0
2020-06-15 00:40:00 270.0
2020-06-15 00:50:00 280.0
[128 rows x 1 columns])
如您所见,这产生了三个垃圾箱,而不是我预期的两个。
我可以做一些不同的事情,比如改变我选择重采样因子的方式(例如,找到时间戳之间的平均时间,并将其乘以(DataFrame 的长度/final_length)应该会产生一个更保守的重采样因子),但在我看来,这将掩盖根本问题。主要是,我很想了解为什么会发生这种情况。这导致...
问题
有谁知道为什么会发生这种情况,以及我可能会采取哪些步骤来确保我们获得所需数量的垃圾箱?我想知道这是否是一个偏移问题 - 也就是说,虽然我们将第一个 bin 中的第一个时间戳视为 DataFrame 中的第一个时间戳,但也许 pandas 实际上是在此之前开始 bin 的?
对于任何想在家一起玩的人,测试 DataFrame 可以是 found here 格式的 .csv。将其作为 DataFrame 获取:
df = pd.read_csv('test.csv', parse_dates=[0])
【问题讨论】:
标签: python python-3.x pandas dataframe resampling