Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert number mixed with character to integer in pandas

Tags:

python

pandas

I want to convert a columns where the elements have a type liked number mixed with character, and I want to convert the column to Integer type.

Input:

df = pd.DataFrame({'id':['Q001','Q021']})

Output:

    id
0   Q001
1   Q021

Expected:

    id  idInt
0   Q001    1
1   Q021    21
like image 908
rosefun Avatar asked Dec 10 '22 04:12

rosefun


1 Answers

Or use pd.Series.str.replace with regex of '\D+' being replaced with '' in each string:

df['idInt']=df['id'].str.replace('\D+','').astype(int)

And now:

print(df)

Is:

     id  idInt
0  Q001      1
1  Q021     21    
like image 176
U12-Forward Avatar answered Jan 18 '23 23:01

U12-Forward