0

I have a data frame with a column for number of reviews the dataframe column is listed in this format

816 ratings
1,139 ratings
5 ratings
22,3456 ratings

Id like to convert this to an integer so I can sort the dataframe. My output should be

816
1139
5
223456

I tried

df=df['num_reviews'].str.extract('(\d+)').astype(float)
df

however this converted everything after the comma into a decimal. (i.e. 22,3456 returns 22.0) and using .astype(int) gave me errors due to fields having NaN

3
  • df=df['num_reviews'].str.replace(r'\D+', '').astype(int)? Commented Nov 2, 2020 at 22:55
  • .astype(int) float returns decimal values Commented Nov 2, 2020 at 22:55
  • when i use that i get this following error "cannot convert float NaN to integer" your code worked however if i use float so thank you! I just need to be able to sort Commented Nov 2, 2020 at 22:57

1 Answer 1

1
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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.