0
1

More than 1 year has passed since last update.

pandasのresampleにおけるffillの挙動

Posted at

不定間隔でサンプリングされたデータのリサンプリング

df.resample('1ms').ffill()

としたら、NaNだらけになって???となったので、その時のメモ。

結論

df.ffill().resample('1ms').ffill()

とすればいいみたい。
resampleにおけるffillは、あくまでリサンプリング時に、データがないものをfillするだけで、
直前のデータがNaNだと、NaNで埋められる。
言われるとそうだけど、2回ffill呼ぶのが気持ち悪い。。。

import pandas as pd
import io

df = pd.read_csv(io.StringIO("""
col1,col2
2020-10-19 13:27:43.038572032,,15
2020-10-19 13:27:43.041051392,,25
2020-10-19 13:27:43.043462656,30,35
2020-10-19 13:27:43.045890304,40,
2020-10-19 13:27:43.055974656,,55
2020-10-19 13:27:43.058358016,60,
2020-10-19 13:27:43.060819456,70,35
2020-10-19 13:27:43.063246848,,25
2020-10-19 13:27:43.065672192,,
2020-10-19 13:27:43.074975040,,5
"""), index_col=0, parse_dates=True)
print(df.to_markdown())
col1 col2
2020-10-19 13:27:43.038572032 nan 15
2020-10-19 13:27:43.041051392 nan 25
2020-10-19 13:27:43.043462656 30 35
2020-10-19 13:27:43.045890304 40 nan
2020-10-19 13:27:43.055974656 nan 55
2020-10-19 13:27:43.058358016 60 nan
2020-10-19 13:27:43.060819456 70 35
2020-10-19 13:27:43.063246848 nan 25
2020-10-19 13:27:43.065672192 nan nan
2020-10-19 13:27:43.077975040 nan 5

というデータがあった場合

resample('1ms').ffill() だと

print(df.resample('5ms').ffill().to_markdown())
col1 col2
2020-10-19 13:27:43.035000 nan nan
2020-10-19 13:27:43.040000 nan 15
2020-10-19 13:27:43.045000 30 35
2020-10-19 13:27:43.050000 40 nan
2020-10-19 13:27:43.055000 40 nan
2020-10-19 13:27:43.060000 60 nan
2020-10-19 13:27:43.065000 nan 25
2020-10-19 13:27:43.070000 nan nan

あらかじめffillすると

print(df.ffill().resample('5ms').ffill().to_markdown())
col1 col2
2020-10-19 13:27:43.035000 nan nan
2020-10-19 13:27:43.040000 nan 15
2020-10-19 13:27:43.045000 30 35
2020-10-19 13:27:43.050000 40 35
2020-10-19 13:27:43.055000 40 35
2020-10-19 13:27:43.060000 60 55
2020-10-19 13:27:43.065000 70 25
2020-10-19 13:27:43.070000 70 25

注意

初めと最後のデータの扱いは、チェックしたほうがいいかも。

初めのデータは、切り捨てられたところから始まるから、その時には計測データないので当然NaNだし、
最後のデータは、切り捨てられたところで終わるので、含まれない。
この辺はちょっと気持ち悪いね。

あと、あたりまえだけどffillだと、同じ区間に複数回計測データがあっても、
その区間の最後の値にしかならないので、それでいいかどうかも確認が必要。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1