【问题标题】:Pandas Interpolate dataframe with new lengthPandas 插入具有新长度的数据帧
【发布时间】:2016-08-06 00:24:56
【问题描述】:

我有一个包含 Datetime、lat、lon、z 列的数据框。我正在从 csv 文件中读取数据,因此设置日期时间的时间段不起作用。时间间隔为 6 小时,但我想将数据线性插值到每小时间隔。

       'A'              'B'    'C'   'D'
0   2010-09-13 18:00:00 16.3 -78.5    1
1   2010-09-14 00:00:00 16.6 -79.8    6 
2   2010-09-14 06:00:00 17.0 -81.1    12

       'A'              'B'    'C'   'D'
1   2010-09-13 18:00:00 16.3  -78.5   1      
2   2010-09-13 19:00:00 16.35 -78.7   2
3   2010-09-13 20:00:00 16.4  -78.9   3
4   2010-09-13 21:00:00 16.45 -79.1   4
5   2010-09-13 22:00:00 16.5  -79.3   5
....

我已尝试使用 interpolate 命令,但没有参数用于新的数据帧长度。

df.interpolate(method='linear')

我在想我可以使用 .loc 在数据帧的每一行之间包含 5 行 NAN,然后使用插值函数,但这似乎是一个不好的解决方法。

解决方案 如果您的初始列未作为日期时间导入,则使用 DatetimeIndex 会消除与其他列的关联。

i = pd.DatetimeIndex(start=df['A'].min(), end=df['A'].max(),    freq='H')
df = df.reindex(i).interpolate()
print(df)

给出正确答案。

【问题讨论】:

  • 样本数据只有日期时间、纬度、经度……z在哪里?

标签: python pandas linear-interpolation


【解决方案1】:
i = pd.DatetimeIndex(start=df.index.min(), end=df.index.max(), freq='H')
df = df.reindex(i).interpolate()
print(df)

输出

2010-09-13 18:00:00  16.300000 -78.500000
2010-09-13 19:00:00  16.350000 -78.716667
2010-09-13 20:00:00  16.400000 -78.933333
2010-09-13 21:00:00  16.450000 -79.150000
2010-09-13 22:00:00  16.500000 -79.366667
  1. 使用DatetimeIndex (docs) 创建具有所需频率的新索引。

  2. reindex (docs) 使用这个新索引。默认情况下,新索引的值为 np.nan

  3. interpolate (docs) 来填补这些缺失值。您可以提供method kwarg 来确定如何进行插值。

【讨论】:

  • 因此,假设纬度/经度具有日期时间索引开始,则此方法有效。但是如果原始索引是 1-3 并且时间在标记为“A”的第一列中怎么办?
  • 您可以使用set_index (docs) 将该列用作索引。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 2019-10-11
  • 1970-01-01
  • 1970-01-01
  • 2011-07-17
  • 1970-01-01
相关资源
最近更新 更多