Pandas.to_numeric - find out which string he could not parse

Applying a pandas.to_numericdataframe to a column that contains rows that represent numbers (and possibly other inalienable rows) results in an error message that resembles the following:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-66-07383316d7b6> in <module>()
      1 for column in shouldBeNumericColumns:
----> 2     trainData[column] = pandas.to_numeric(trainData[column])

/usr/local/lib/python3.5/site-packages/pandas/tools/util.py in to_numeric(arg, errors)
    113         try:
    114             values = lib.maybe_convert_numeric(values, set(),
--> 115                                                coerce_numeric=coerce_numeric)
    116         except:
    117             if errors == 'raise':

pandas/src/inference.pyx in pandas.lib.maybe_convert_numeric (pandas/lib.c:53558)()

pandas/src/inference.pyx in pandas.lib.maybe_convert_numeric (pandas/lib.c:53344)()

ValueError: Unable to parse string

Wouldn't it be useful to know what value could not be analyzed?

+4
source share
2 answers

I think you can add a parameter errors='coerce'to convert bad non-numeric values ​​to NaN, and then check these values isnulland use boolean indexing:

print (df[pd.to_numeric(df.col, errors='coerce').isnull()])

Example:

df = pd.DataFrame({'B':['a','7','8'],
                   'C':[7,8,9]})

print (df)
   B  C
0  a  7
1  7  8
2  8  9

print (df[pd.to_numeric(df.B, errors='coerce').isnull()])
   B  C
0  a  7

, - type if is string:

df = pd.DataFrame({'B':['a',7, 8],
                   'C':[7,8,9]})

print (df)
   B  C
0  a  7
1  7  8
2  8  9

print (df[df.B.apply(lambda x: isinstance(x, str))])
   B  C
0  a  7
+11

, , , , . . , , , .

import pandas as pd
import re

non_numeric = re.compile(r'[^\d.]+')

df = pd.DataFrame({'a': [3,2,'NA']})
df.loc[df['a'].str.contains(non_numeric)]
+1

Source: https://habr.com/ru/post/1661867/


All Articles