Pandas での修正方法: 文字列を浮動小数点に変換できない
パンダの使用時に発生する可能性のある一般的なエラーは次のとおりです。
ValueError : could not convert string to float: '$400.42'
このエラーは通常、文字列に次の 1 つ以上が含まれている場合に、パンダで文字列を float に変換しようとしたときに発生します。
- スペース
- カンマ
- 特殊文字
この問題が発生した場合は、文字列を float に変換する前に、まず文字列からこれらの文字を削除する必要があります。
次の例は、このエラーを実際に解決する方法を示しています。
エラーを再現する方法
次のパンダ データフレームがあるとします。
import pandas as pd #createDataFrame df = pd. DataFrame ({' store ': ['A', 'B', 'C', 'D'], ' revenue ': ['$400.42', '$100.18', '$243.75', '$194.22']}) #view DataFrame print (df) store revenue 0 A $400.42 1 B $100.18 2 C $243.75 3D $194.22 #view data type of each column print ( df.dtypes ) store object revenue object dtype:object
ここで、収益列を文字列から浮動小数点数に変換しようとしているとします。
#attempt to convert 'revenue' from string to float
df[' revenue '] = df[' revenue ']. astype (float)
ValueError : could not convert string to float: '$400.42'
収入列の文字列にドル記号が含まれているため、エラーが発生します。
エラーを修正する方法
このエラーを解決する方法は、変換を実行する前にreplace()関数を使用して収入列のドル記号を何も置換しないことです。
#convert revenue column to float
df[' revenue '] = df[' revenue ']. apply ( lambda x: float(x. split ()[ 0 ]. replace (' $ ', '')))
#view updated DataFrame
print (df)
store revenue
0 to 400.42
1 B 100.18
2 C 243.75
3 D 194.22
#view data type of each column
print ( df.dtypes )
store object
income float64
dtype:object
収益列を文字列から浮動小数点数に変換でき、変換を行う前にドル記号を削除したため、エラーが発生していないことに注意してください。
追加リソース
次のチュートリアルでは、Python の他の一般的なエラーを修正する方法を説明します。
Python で修正する方法: オブジェクト ‘numpy.ndarray’ は呼び出し可能ではありません
修正方法: TypeError: オブジェクト ‘numpy.float64’ は呼び出し可能ではありません
修正方法: 型エラー: 文字列またはバイト オブジェクトが必要です