python - 如何使用时间戳对 Pandas DataFrame 进行上采样

标签 python pandas resampling

我有一个像这样的 DataFrame(不关心 NaN 值):

enter image description here

我想每 20 毫秒对其进行一次上采样。

我所做的是:

df = df.set_index('TIMESTAMP')
df = df.resample('20ms').ffill()

但我收到错误:

Traceback (most recent call last):
sens_encoded = sens_encoded.resample('20ms').ffill()
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'

所以我尝试将 TIMESTAMP 转换为 DateTime,它应该已经是:

df = df.set_index('TIMESTAMP')
df.index = pd.to_datetime(df.index)   //Added this
df = df.resample('20ms').ffill()

但我收到错误:

Traceback (most recent call last):
df.index = pd.to_datetime(df.index)
TypeError: <class 'tuple'> is not convertible to datetime

编辑:

我认为问题可能是在 set_index('TIMESTAMP') 之后,数据帧看起来像这样(注意时间戳值中的括号):

enter image description here

编辑2:

我发现为什么我在 df 中得到这些括号。 这是因为我在创建它时将列名称指定为方括号内的列表。正确的做法是:

columns_names = ['D07', 'C10', ...]
df = pd.DataFrame(columns=columns_names)

df = pd.DataFrame(columns=[columns_names])

最佳答案

首先将MultiIndex的第一级设置为列,以删除损坏的一级MultiIndex

添加参数errors='coerce',用于将不可解析的值转换为NaT(如有必要),也可以先转换列,然后创建DatetimeIndex 和最后一个上采样:

df.columns = df.columns.get_level_values(0)

df['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP'], errors='coerce')
df = df.set_index('TIMESTAMP').resample('20ms').ffill()

或者:

df.columns = df.columns.get_level_values(0)

df = df.set_index('TIMESTAMP')
df.index = pd.to_datetime(df.index, errors='coerce')
df = df.resample('20ms').ffill()

关于python - 如何使用时间戳对 Pandas DataFrame 进行上采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53361618/

相关文章:

R采样绕过randomForest 32因子限制

python - 如何通过复制/跳过每 N 个项目来重新采样数组?

python - 扁平化python中每个键的值

python - 将日期转换为小时

python - 更改 pandas MultiIndex 的字符串编码

python - 从 Pandas Dataframe 创建 Numpy 数组时丢失字符串

python - 编写 python 函数以从 pandas 数据框中提取匹配行

r - 从基准实验中使用的重采样获取ResamplingIndices - mlr

python - 理解这一行 : list_of_tuples = [(x, y) for x, y, label in data_one]

python - 如何使用python查找列表中最大数字出现的次数?