AttributeError 'Series' object has no attribute 'to_numeric'

2.1k Views Asked by At

I have A pandas dataframe, and I want to change the content of a column, depending on its current value. If the record has the value 'INFINITY', assign a constant, elsewhere, assign its current value casted to number. This is my code so far:

data_frame['my_column'] = np.where(data_frame['my_column'] == 'INFINITY', 999999999999, data_frame['my_column'].to_numeric())

The problem is that this code raises this exception:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
C:\Users\HUGO~1.VIL\AppData\Local\Temp/ipykernel_28924/1872682007.py in <module>
----> 1 data_frama['my_column'] = np.where(data_frame['my_column'] == 'INFINITY', 999999999999, data_frame['my_column'].to_numeric())

~\Documents\code\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   5485         ):
   5486             return self[name]
-> 5487         return object.__getattribute__(self, name)
   5488 
   5489     def __setattr__(self, name: str, value) -> None:

AttributeError: 'Series' object has no attribute 'to_numeric'

How can I instruct NumPy where to take the current value and cast it to number?

1

There are 1 best solutions below

0
mozway On BEST ANSWER

Your issue had nothing to do with where. to_numeric is not a valid Series method. However, the top level pandas.to_numeric method exists.

Thus, you should replace data_frame['my_column'].to_numeric() with:

import pandas as pd
pd.to_numeric(data_frame['my_column'])

In your context:

data_frame['my_column'] = np.where(data_frame['my_column'] == 'INFINITY', 999999999999, pd.to_numeric(data_frame['my_column']))