0

I have a csv that has a column called 'ra'.

This is the first 'ra' value the csv has: 8570.0 - I will use it as an example.

I need to remove '.0'.

So I've tried:

dtypes = {

'ra': 'str',

}

df['ra_csv'] = pd.DataFrame({'ra_csv':df['ra']}).replace('.0', '', regex=true).astype(str)

This code returns me '85' instead of '8570'. It's replacing all the 0s, and somehow removed the number '7' aswell.

How can I make it return '8750'? Thanks.

5
  • @Ch3steR, regex=False returns '8570.0', it doesnt replace '.0'. Commented Feb 28, 2021 at 18:01
  • check dtype? its a float or a string? too many question marks without a proper reproducible example. Commented Feb 28, 2021 at 18:02
  • @anky, it's a string. Commented Feb 28, 2021 at 18:03
  • @fsimoes Please add your dataframe to the question. You can edit your question from here. And what's the output of print(df.dtypes)? Commented Feb 28, 2021 at 18:05
  • Not sure if all the rows have valid data but based on sample df, using to_numeric might be more appropriate here, pd.to_numeric(df['ra_csv']).astype(int) Commented Feb 28, 2021 at 18:06

2 Answers 2

2

Option 1: use to_numeric to first convert the data to numeric type and convert to int,

df['ra_csv'] = pd.to_numeric(df['ra_csv']).astype(int)

Option 2: using str.replace

df['ra_csv'] = df['ra_csv'].str.replace('\..*', '')

You get

    ra_csv
0   8570
Sign up to request clarification or add additional context in comments.

Comments

1

The regex pattern .0 has two matches in your string '8570.0'. . matches any character.

  • 70
  • .0

Since you are using df.replace setting regex=False wouldn't because it checks for exact matches only. From docs df.replace:

str: string exactly matching to_replace will be replaced with value

Possible fixes are either fix your regex or use pd.Series.str.replace

  • Fixing your regex

    df.replace('\.0', '', regex=True)
    
  • Using str.replace

    df['ra'].str.replace('.0', '', regex=False)
    

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.