Reputation: 137
I created the following class to convert objects to a numeric type:
class ConvertObjectToNum:
def convert(dataframe, column):
dataframe[column] = dataframe[column].apply(lambda x: pd.to_numeric(x, errors = 'coerce'))
When calling the class like this
data_set['Qual'] = ConvertObjectToNum.convert('data_set', 'Qual')
I get the following error:
<ipython-input-20-4d0c321cdb16> in convert(dataframe, column)
1 class ConvertObjectToNum:
2 def convert(dataframe, column):
----> 3 dataframe[column] = dataframe[column].apply(lambda x: pd.to_numeric(x, errors = 'coerce'))
4
5
TypeError: string indices must be integers
However, calling the to_numeric function outside of my class works just fine. So I guess it has to be a problem with how I constructed the class:
data_set['Qual'] = data_set['Qual'].apply(lambda x: pd.to_numeric(x, errors = 'coerce'))
Thanks for your help
E:
The values of the column are numbers in a String format. With some '-' mixed in, hence the Errors = 'coerce' parameter.
Upvotes: 0
Views: 188
Reputation: 12339
Here's a solution.
import pandas as pd
class ConvertObjectToNum:
@staticmethod
def convert(dataframe, column):
dataframe[column] = dataframe[column].apply(lambda x: pd.to_numeric(x, errors = 'coerce'))
df = pd.DataFrame({'Weight': [45, 88, 56, 15, 71]})
ConvertObjectToNum.convert(df, 'Weight')
print (df.dtypes) # Weight int64
I made the method a staticmethod.
Upvotes: 1
Reputation: 511
Maybe this approach will do the work:
df['col'] = pd.to_numeric(df['col'])
The class:
class ConvertObjectToNum:
def convert(dataframe, column):
dataframe[column] = pd.to_numeric(df[column])
Upvotes: 0