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

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

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

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

Q&A

解決済

2回答

2625閲覧

object型からint型に変換したいが''のせいでできない?

Pablito

総合スコア71

Python 3.x

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

0グッド

0クリップ

投稿2020/02/06 09:32

前提・実現したいこと

object型でインポートされたデータフレームの中の値を
全てint型にしたいと思っております。

しかし、数値が''で囲まれているようで、
.replace("''", '')で対処しようとしたのですが、
中々うまくいきません。

下記はデータの一部です。

months total organic guests 0 Jan 1,021,069 561,101 103,929

発生している問題・エラーメッセージ

--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-8-b66f6148172e> in <module> 1 df = df.replace("''", '') ----> 2 df = df.astype(int) 3 df.info() c:\users\lib\site-packages\pandas\core\generic.py in astype(self, dtype, copy, errors) 5695 else: 5696 # else, only a single dtype is given -> 5697 new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors) 5698 return self._constructor(new_data).__finalize__(self) 5699 c:\users\lib\site-packages\pandas\core\internals\managers.py in astype(self, dtype, copy, errors) 580 581 def astype(self, dtype, copy: bool = False, errors: str = "raise"): --> 582 return self.apply("astype", dtype=dtype, copy=copy, errors=errors) 583 584 def convert(self, **kwargs): c:\users\lib\site-packages\pandas\core\internals\managers.py in apply(self, f, filter, **kwargs) 440 applied = b.apply(f, **kwargs) 441 else: --> 442 applied = getattr(b, f)(**kwargs) 443 result_blocks = _extend_blocks(applied, result_blocks) 444 c:\users\lib\site-packages\pandas\core\internals\blocks.py in astype(self, dtype, copy, errors) 623 vals1d = values.ravel() 624 try: --> 625 values = astype_nansafe(vals1d, dtype, copy=True) 626 except (ValueError, TypeError): 627 # e.g. astype_nansafe can fail on object-dtype of strings c:\users\lib\site-packages\pandas\core\dtypes\cast.py in astype_nansafe(arr, dtype, copy, skipna) 872 # work around NumPy brokenness, #1987 873 if np.issubdtype(dtype.type, np.integer): --> 874 return lib.astype_intsafe(arr.ravel(), dtype).reshape(arr.shape) 875 876 # if we have a datetime/timedelta array of objects pandas\_libs\lib.pyx in pandas._libs.lib.astype_intsafe() ValueError: invalid literal for int() with base 10: '1,021,069'

該当のソースコード

Python

1data = pd.read_csv(path, sep=',') 2data.info() 3""" 4<class 'pandas.core.frame.DataFrame'> 5RangeIndex: 13 entries, 0 to 12 6Data columns (total 4 columns): 7 # Column Non-Null Count Dtype 8--- ------ -------------- ----- 9 0 months 13 non-null object 10 1 total 13 non-null object 11 2 organic 13 non-null object 12 3 guests 13 non-null object 13dtypes: object(4) 14memory usage: 272.0+ bytes 15""" 16df = data.drop('months', axis=1) 17df = df.replace("''", '') 18df = df.astype(int) 19df.info()

何卒宜しくお願い致します。

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

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

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

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

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

guest

回答2

0

ベストアンサー

ValueError: invalid literal for int() with base 10: '1,021,069'とのことなので、カンマ,が含まれているのが原因ですのでreplace(',','', regex=True)のようにしてください。
なお、文字列の一部を置換したいのでregex=Trueが必要です。
指定しないと,という値と完全一致するセル値しか置換されません。

投稿2020/02/06 10:21

can110

総合スコア38262

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

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

magichan

2020/02/06 10:26

DataFrame.replace() で正規表現の文字列置換が行えたのですね。 完全一致だけかと思ってました。
can110

2020/02/06 10:33

置換されないので「なんで?」と思ってマニュアル確認したら載ってました。一括処理できるので便利ですね。
guest

0

df.replace() は要素の値を入れ替える(完全一致で入れ替わる)為のものなので、文字列の一部を置き換える用途には使えません。

今回のように文字列の一部を置き換えるためには Series.str.replace() を使用してください。

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html

ただこれは DataFrameではなくSeries に対するMethodですので、DataFreme.apply() 等で列毎に適用する必要がありますので

Python

1df = df.apply(lambda d: d.str.replace(',', '')).astype(int)

のように記述する必要があります。
ということで上記の方法で ','を削除した後に astype(int)を行うとよいのではないでしょうか。

動作確認

Python

1import pandas as pd 2df = pd.DataFrame([['Jan','1,021,069','561,101','103,929']], 3 columns = ['months','total','organic','guests']) 4 5df = df.drop('months', axis=1) 6df = df.apply(lambda d: d.str.replace(',', '')).astype(int) 7 8print(df) 9# total organic guests 10#0 1021069 561101 103929 11 12df.info() 13#<class 'pandas.core.frame.DataFrame'> 14#RangeIndex: 1 entries, 0 to 0 15#Data columns (total 3 columns): 16# # Column Non-Null Count Dtype 17#--- ------ -------------- ----- 18# 0 total 1 non-null int64 19# 1 organic 1 non-null int64 20# 2 guests 1 non-null int64 21#dtypes: int64(3) 22#memory usage: 152.0 bytes

投稿2020/02/06 10:21

magichan

総合スコア15898

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問