質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

3504閲覧

pythonでdfにスプライン補間ができない

umimarine

総合スコア6

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2021/08/28 14:37

編集2021/08/28 16:23

・NaNが含まれているデータに対して、3次のスプライン補間をしてNaNをなくしたい。
・データはintとNaN、256列、22行。df=データフレーム。
・スクリプトは以下。

Python3

1df.interpolate('spline',order = 3,inplace = True,limit_direction='both')

エラーコードは以下。

--------------------------------------------------------------------------- error Traceback (most recent call last) <ipython-input-141-e0191a4a1ce5> in <module> ----> 1 df.interpolate('spline',order = 3,inplace = True,limit_direction='both') /Applications/anaconda3/lib/python3.8/site-packages/pandas/core/generic.py in interpolate(self, method, axis, limit, inplace, limit_direction, limit_area, downcast, **kwargs) 7220 "those NaNs before interpolating." 7221 ) -> 7222 new_data = obj._mgr.interpolate( 7223 method=method, 7224 axis=axis, /Applications/anaconda3/lib/python3.8/site-packages/pandas/core/internals/managers.py in interpolate(self, **kwargs) 591 592 def interpolate(self, **kwargs) -> "BlockManager": --> 593 return self.apply("interpolate", **kwargs) 594 595 def shift(self, periods: int, axis: int, fill_value) -> "BlockManager": /Applications/anaconda3/lib/python3.8/site-packages/pandas/core/internals/managers.py in apply(self, f, align_keys, ignore_failures, **kwargs) 425 applied = b.apply(f, **kwargs) 426 else: --> 427 applied = getattr(b, f)(**kwargs) 428 except (TypeError, NotImplementedError): 429 if not ignore_failures: /Applications/anaconda3/lib/python3.8/site-packages/pandas/core/internals/blocks.py in interpolate(self, method, axis, index, inplace, limit, limit_direction, limit_area, fill_value, coerce, downcast, **kwargs) 1280 assert index is not None # for mypy 1281 -> 1282 return self._interpolate( 1283 method=m, 1284 index=index, /Applications/anaconda3/lib/python3.8/site-packages/pandas/core/internals/blocks.py in _interpolate(self, method, index, fill_value, axis, limit, limit_direction, limit_area, inplace, downcast, **kwargs) 1371 1372 # interp each column independently -> 1373 interp_values = np.apply_along_axis(func, axis, data) 1374 1375 blocks = [self.make_block_same_class(interp_values)] <__array_function__ internals> in apply_along_axis(*args, **kwargs) /Applications/anaconda3/lib/python3.8/site-packages/numpy/lib/shape_base.py in apply_along_axis(func1d, axis, arr, *args, **kwargs) 400 buff[ind0] = res 401 for ind in inds: --> 402 buff[ind] = asanyarray(func1d(inarr_view[ind], *args, **kwargs)) 403 404 if not isinstance(res, matrix): /Applications/anaconda3/lib/python3.8/site-packages/pandas/core/internals/blocks.py in func(yvalues) 1358 # should the axis argument be handled below in apply_along_axis? 1359 # i.e. not an arg to missing.interpolate_1d -> 1360 return missing.interpolate_1d( 1361 xvalues=index, 1362 yvalues=yvalues, /Applications/anaconda3/lib/python3.8/site-packages/pandas/core/missing.py in interpolate_1d(xvalues, yvalues, method, limit, limit_direction, limit_area, fill_value, bounds_error, order, **kwargs) 277 ) 278 else: --> 279 result[invalid] = _interpolate_scipy_wrapper( 280 inds[valid], 281 yvalues[valid], /Applications/anaconda3/lib/python3.8/site-packages/pandas/core/missing.py in _interpolate_scipy_wrapper(x, y, new_x, method, fill_value, bounds_error, order, **kwargs) 346 f"order needs to be specified and greater than 0; got order: {order}" 347 ) --> 348 terp = interpolate.UnivariateSpline(x, y, k=order, **kwargs) 349 new_y = terp(new_x) 350 else: /Applications/anaconda3/lib/python3.8/site-packages/scipy/interpolate/fitpack2.py in __init__(self, x, y, w, bbox, k, s, ext, check_finite) 200 201 # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier --> 202 data = dfitpack.fpcurf0(x, y, k, w=w, xb=bbox[0], 203 xe=bbox[1], s=s) 204 if data[-1] == 1: error: (m>k) failed for hidden m: fpcurf0:m=2

線形補間を使うとエラーは出ない。が、

Python3

1 2df.interpolate('linear',inplace = True,limit_direction='both')

結果としては、上(1行目〜)、中、下(〜最終行)までNaNが埋まっていない。

・データを使う目的上、スプライン補間が適しています。
→外挿しても予測値を使ってくれるためです。線形補間だと外挿では予測値を使ってくれません。
・どうしたらスプライン補間が使えるようになるでしょうか?

<08/29 1:19修正>
ppaul様、ご回答ありがとうございます。

スプライン回帰のスクリプト実行後の結果は結局以下のようになっております。
イメージ説明

※NaNが全く置き換えられていない。(外挿、内挿全て。)

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

3次のスプライン補間をするためには、最小限4点のデータが必要です。
保管しようとしているデータの各列の中にNaNでないデータが3点以下しかない列がある場合にこのえらーが起きるようです。

解決策1 各列が少なくとも4点のにNaNでないデータを持つようにする。
解決策2 order = 3を2とか1に下げる。

投稿2021/08/28 15:07

ppaul

総合スコア24666

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

umimarine

2021/08/28 16:24

ありがとうございます。上記のコード動きました。 しかしNaNが結局全く埋まっていない状況になっています。 (データの現状追記いたしました。) こちらの対処方法もしお分かりになれば、お教えくださいますでしょうか?
ppaul

2021/08/29 05:46

この情報だけでは良くわかりませんが、型が違う可能性があります。 print(df['その他棚卸し資産'].dtype) を実行するとdtype('float64')になっていますか? これがdtype('O')だとすると、それが原因です。
umimarine

2021/08/29 12:05

こちら試したところ、その他棚卸し資産はfloat64だったのですが、 その他棚卸し資産,以外にもtypeを調べたところ、一部str型になっておりました。全てfloatにしたところ、NaNが全て補完されました。 ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問