Monday, October 17, 2022

[FIXED] How to convert an object dtype to integer by removing letter characters?

Issue

I have the following dataframe:

data = {'id':['9011001', '9011001-83V', '9011001-78G', '9011001-56V'],
        'av':[0, 1, 0, 1]}
 
df = pd.DataFrame(data)

The df.dtypes are:

id     object
av     int64
dtype: object

I would like to convert the id object column to an integer one. I understand that I cannot do this since the column contains letters as well. I was thinking to delete the letter characters from this column so I can make the conversion after by using df['id'].astype(int).

Do you have any idea on how I can delete the letter characters from the id column?

Thank you in advance.


Solution

here is one way to to it using regex

# \d : digit character
#[^\d] : match for non-digit character

df['id'].str.replace(r'[^\d]','', regex=True)
0      9011001
1    901100183
2    901100178
3    901100156
Name: id, dtype: object


Answered By - Naveed
Answer Checked By - Robin (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.