【问题标题】:Pandas: interpolation where first and last data point in column is NaNPandas:插值,其中列中的第一个和最后一个数据点是 NaN
【发布时间】:2018-05-24 12:19:41
【问题描述】:

我想使用 interpolate 函数,但仅限于 pandas DataFrame 列中的已知数据值之间。问题是列中的第一个和最后一个值通常是 NaN,有时在一个值不是 NaN 之前它可能是很多行:

      col 1    col 2
 0    NaN      NaN
 1    NaN      NaN
...
1000   1       NaN
1001  NaN       1   <-----
1002   3       NaN  <----- only want to fill in these 'in between value' rows
1003   4        3
...
3999  NaN      NaN
4000  NaN      NaN

我正在将一个数据集捆绑在一起,该数据集在“事件”时更新,但对于每一列都是单独的,并通过时间戳进行索引。这意味着通常有一些行没有记录某些列的数据,因此有很多 NaN!

【问题讨论】:

  • 能把tying together a dataset的代码和数据贴出来吗?
  • 嗯,数据非常大,但如果可以的话,我会添加一个片段......我使用一个简单的 pd.concat 将其连接在一起,它填充了未为同一索引记录数据的 NaN在被连接的任一数据帧中: pdDataFrame_ToAppend = pd.concat([pdDataFrame_ToAppend,tempData], join='outer')

标签: python pandas interpolation


【解决方案1】:

我通过函数idxmin和idxmax按列的min和max值选择,并使用函数fillna和方法前向填充。

print df
#      col 1  col 2
#0       NaN    NaN
#1       NaN    NaN
#1000      1    NaN
#1001    NaN      1
#1002      3    NaN
#1003      4      3
#3999    NaN    NaN
#4000    NaN    NaN

df.loc[df['col 1'].idxmin(): df['col 1'].idxmax()] = df.loc[df['col 1'].idxmin(): df['col 1'].idxmax()].fillna(method='ffill')
df.loc[df['col 2'].idxmin(): df['col 2'].idxmax()] = df.loc[df['col 2'].idxmin(): df['col 2'].idxmax()].fillna(method='ffill')
print df
#      col 1  col 2
#0       NaN    NaN
#1       NaN    NaN
#1000      1    NaN
#1001      1      1
#1002      3      1
#1003      4      3
#3999    NaN    NaN
#4000    NaN    NaN

添加了不同的解决方案,谢谢HStro。

df['col 1'].loc[df['col 1'].first_valid_index() : df['col 1'].last_valid_index()] = df['col 1'].loc[df['col 1'].first_valid_index(): df['col 1'].last_valid_index()].astype(float).interpolate()

【讨论】:

  • 看起来很酷。你知道你是否可以以同样的方式使用插值?
  • 你可以试试apply(pandas.Series.interpolate)而不是fillna。
  • 好的,我会试一试,让你知道,为帮助干杯!
  • 是的,它起作用了,不过我不得不稍微改变一下。我用这个: df_azure[col].loc[df_azure[col].first_valid_index() : df_azure[col].last_valid_index()] = df_azure[col].loc[df_azure[col].first_valid_index(): df_azure[col] .last_valid_index()].astype(float).interpolate()
猜你喜欢
  • 2015-09-28
  • 2014-04-19
  • 2017-11-28
  • 2019-12-09
  • 2017-08-25
  • 2014-10-11
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多