How to remove '.0', or the decimal point from string values in a column that also contains values that are text?

Viewed 50

Consider the following dataframe:

Store Number Count
1.0 121
2.0 85
3.0 32
ABC 89
BCD 94
CDE 4

I want to remove the '.0' from the store number. The dtype is string. I want the output to look like this:

Store Number Count
1 121
2 85
3 32
ABC 89
BCD 94
CDE 4

I have tried: df = df['Store Number'].replace('.0','')

as well as: df = df['Store Number'].replace('.\d0','')

4 Answers

This should work.

x = df['Store Number'].split('.')[0]

This will allow you to access the number to the left of the decimal.

The final code that worked for me was:

df['Store Number'] = df['Store Number'].str.replace(r"\.0",'')

You can write it as:

df['Store Number'] = df['Store Number'].str.replace('.0','')

print(df)

Output

  Store Number Count
0            1   121
1            2    85
2            3    32
3          ABC    89
4          BCD    94
5          CDE     4

Here's a testable alternative that broadens regex matching a bit.

  • No digit after decimal point
  • Single or many digits/characters after decimal point
  • Blank spaces after decimal point

    # Sample data
    d = { 'A': '1.0', 'B': '2.02333', 'C': '3.011333axxd', 'D': 'ABC', 'E': '1.', 'F': 'CDE' }
    
    df = pd.DataFrame([d])
    df.iloc[0] = df.iloc[0].str.replace('(\.).*', '', regex=True)
    print(df)

This example is performing replacement over the entire column at index zero. It's worth mentioning that this solution doesn't perform inline type casting, as the sample values are all strings.

Related