0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pandas 列単位のデータ型の変換メモ

Posted at

数値型列に数値以外のデータが入っていた時の対応

DataFrameでは列にひとつでも数値以外のValueがあるとObject型に認識されるようです。これをそのまま数値型に変換しようとするとエラーになります。
数値型に変換するために文字列を探して、ひとつひとつ対応することになりますが、
文字列を完全に無視してよい場合は簡単な方法がありました。

to_numric関数の引数errorsにcoerceを渡す

coerceは強制という意味らしいです。数値以外のデータがNanになります。
元の文字列データが消えてしまうので注意が必要ですが、テスト的に手っ取り早く型変換したい場合に便利でした。


df_s["test"] = pd.to_numeric(df_s["test"] , errors="coerce")

df_s.info()
test          933 non-null float64
dtypes: datetime64[ns](2), float64(11), int64(3), object(16)
memory usage: 233.6+ KB
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?