top of page

[python] Determine if the string is a number (including decimals)


What I want to do


I want to determine if a given string is a number.



Problem


Python has a method called isnumeric () that determines whether a string is a number, but if it is a decimal, "." is regarded as a character.

"1".isnumeric()   
# True

"1.2".isnumeric()   
# False


Solution


There seems to be no method to judge the decimal number, so I will make it myself.

Cast with float (), and if an exception occurs, judge it as a character string.

def is_float(x):
    
    try:
        y=float(x)
        return True
    except:
        return False
is_float("1.2")
# True

is_float("a")
# False


Application


I ran into this problem while reading and processing data from a csv file. It was a "dirty" data file where the part without data was a character string "" or there was a comment like "confirmation required". In such a case, the above method was used to extract the number part (including decimals, of course) of the data.

import pandas as pd

#read data
df=pd.read_csv('data.csv')

#extract number
df=df[df['data1'].map(is_float)]

Recent Posts

See All

[Python] Conditionally fitting

Overview If you want to do fitting, you can do it with scipy.optimize.leastsq etc. in python. However, when doing fitting, there are many...

Comentários


category

Let's do our best with our partner:​ ChatReminder

iphone6.5p2.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Let's do our best with our partner:​ ChatReminder

納品:iPhone6.5①.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Theme diary: Decide the theme and record for each genre

It is a diary application that allows you to post and record with themes and sub-themes for each genre.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png
bottom of page