PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 17, 2022

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

 October 17, 2022     integer, object, pandas, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing