convert a string in a pandas dataframe to an integer

df['num_reviews'].str.replace(r'\D+', '').replace('','0').astype(float)

Test case:

df = pd.DataFrame({
    'num_reviews': ["816 ratings", "1,139 ratings", 
                    "5 ratings", "no ratings", "22,3456 ratings"]
})
print (df['num_reviews'].str.replace(r'\D+', '').replace('','0').astype(float))

Output:

0       816.0
1      1139.0
2         5.0
3         0.0
4    223456.0

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top