0

I have a Pandas dataframe that has a column owner_type that reads first, second, third etc. I am trying to first replace these categorical variable with numeric values 1, 2, 3 and then cast to a float before applying a linear regression model on the dataframe. When I use replace to do this, I get all empty values returned.

My end goal : Convert categorical variable of owner_type into a numeric value.

Code I used.

cardata['Owner_Type'] = cardata['Owner_Type'].str.replace(r'[\xa0]',"")  
cardata['Owner_Type'] = cardata['Owner_Type'].replace(['First'], '1', inplace = True)
cardata['Owner_Type'] = cardata['Owner_Type'].replace(['Second'], '2', inplace = True)
cardata['Owner_Type'] = cardata['Owner_Type'].replace(['Third'], '3', inplace = True)
cardata['Owner_Type'] = cardata['Owner_Type'].replace(['Fourth'], '4', inplace = True)
cardata['Owner_Type'] = cardata['Owner_Type'].replace(['Fourth & Above'], '5', inplace = True)

cardata['Owner_Type'].value_counts()

Output of above code is

Series([], Name: Owner_Type, dtype: int64

What I was expecting for output : [1, 2, 3, 4, 5]

Please help.

eshirvana
  • 23,227
  • 3
  • 22
  • 38
Curious
  • 11
  • 1
  • Please provide a sample of the DataFrame that allows us to reproduce the same output. You should read [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) and [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). – Rodalm Nov 18 '21 at 18:40

1 Answers1

0

maybe this can help. maps your values to float. Anything not mapped changes to NaN. You may need to use fillna(' ') if you really want to show strings.

df = pd.DataFrame({'Owner_Type':['\xa0', 'First', 'Second', 'Third', 'Fourth', 'Fourth & Above']})
df['Owner_Type'].map({'First': 1.0, 'Second': 2.0, 'Third': 3.0, 'Fourth': 4.0, 'Fourth & Above': 5.0}).value_counts()

1.0    1
2.0    1
3.0    1
4.0    1
5.0    1
Name: Owner_Type, dtype: int64
Jonathan Leon
  • 5,440
  • 2
  • 6
  • 14