【发布时间】:2018-05-17 16:06:32
【问题描述】:
如果我有一个类似于这个的df:
print(df)
A B C D E
DATE_TIME
2016-08-10 13:57:00 3.6 A 1 NaN NaN
2016-08-10 13:58:00 4.7 A 1 4.5 NaN
2016-08-10 13:59:00 3.4 A 0 NaN 5.7
2016-08-10 14:00:00 3.5 A 0 NaN NaN
2016-08-10 14:01:00 2.6 A 0 4.6 NaN
2016-08-10 14:02:00 4.8 A 0 NaN 4.3
2016-08-10 14:03:00 5.7 A 1 NaN NaN
2016-08-10 14:04:00 5.5 A 1 5.7 NaN
2016-08-10 14:05:00 5.6 A 1 NaN NaN
2016-08-10 14:06:00 7.8 A 1 NaN 5.2
2016-08-10 14:07:00 8.9 A 0 NaN NaN
2016-08-10 14:08:00 3.6 A 0 NaN NaN
print (df.dtypes)
A float64
B object
C int64
D float64
E float64
dtype: object
感谢社区的大量输入,我现在有了这段代码,它允许我将我的 df 上采样到秒间隔,对不同的dtypes 应用不同的方法
int_cols = df.select_dtypes(['int64']).columns
index = pd.date_range(df.index[0], df.index[-1], freq="s")
df2 = df.reindex(index)
for col in df2:
if col == int_cols.all():
df2[col].ffill(inplace=True)
df2[col] = df2[col].astype(int)
elif df2[col].dtype == float:
df2[col].interpolate(inplace=True)
else:
df2[col].ffill(inplace=True)
我现在正在寻找一种方法,只在我的实际测量值之间进行插值。 interpolate 函数将我的最后一次测量延长到df 结束:
df2.tail()
Out[75]:
A B C D E
2016-08-10 14:07:56 3.953333 A 0 5.7 5.2
2016-08-10 14:07:57 3.865000 A 0 5.7 5.2
2016-08-10 14:07:58 3.776667 A 0 5.7 5.2
2016-08-10 14:07:59 3.688333 A 0 5.7 5.2
2016-08-10 14:08:00 3.600000 A 0 5.7 5.2
但我想在最后一次测量发生时停止此操作(例如在 14:04:00 col['D'] 和 14:06:00 col['D'])并留下 NaN。
它尝试将“limit”和“limit_direction”的零值添加到“both”:
for col in df2:
if col == int_cols.all():
df2[col].ffill(inplace=True)
df2[col] = df2[col].astype(int)
elif df2[col].dtype == float:
df2[col].interpolate(inplace=True,limit=0, limit_direction='both')
else:
df2[col].ffill(inplace=True)
但这并没有改变任何输出。我试图将我找到的解决方案合并到这个问题:Pandas: interpolation where first and last data point in column is NaN 到我的代码中:
for col in df2:
if col == int_cols.all():
df2[col].ffill(inplace=True)
df2[col] = df2[col].astype(int)
elif df2[col].dtype == float:
df2[col].loc[df2[col].first_valid_index(): df2[col].last_valid_index()]=df2[col].loc[df2[col].first_valid_index(): df2[col].last_valid_index()].astype(float).interpolate(inplace=True)
else:
df2[col].ffill(inplace=True)
...但这不起作用,我的float64 列现在纯粹是 NaN...另外,我尝试插入代码的方式,我知道它只会影响float 列。在一个理想的解决方案中,我希望将此first_valid_index():.last_valid_index() 选择也设置为object 和int64 列。有人可以帮助我吗? ..谢谢你
【问题讨论】:
标签: python pandas interpolation