Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert the '10yrs 5mon' categorical value to months

Tags:

python

pandas

converting the column to numeric as pre-processing

Aging
'10yrs 1mon'
'9yrs 8mon'
'25yrs 5mon'

Expected:

'10yrs 1mon'     121
'9yrs 8mon'      116
'25yrs 5mon'     305
like image 368
Vinoth96 Avatar asked Jan 26 '23 10:01

Vinoth96


1 Answers

Use Series.str.extract with casting to integers to new DataFrame and add new column by multiple 12 first and add second column:

import pandas as pd

df1 = df['Aging'].str.extract('(\d+)yrs\s+(\d+)mon').astype(int)
df['new'] = df1[0] * 12 + df1[1]
print (df)
          Aging  new
0  '10yrs 1mon'  121
1   '9yrs 8mon'  116
2  '25yrs 5mon'  305
like image 98
jezrael Avatar answered Jan 29 '23 00:01

jezrael