[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 AllSummary Data analysis is performed using python. The analysis itself is performed using pandas, and the final results are stored in...
Phenomenon I get a title error when trying to import firestore with raspberry pi. from from firebase_admin import firestore ImportError:...
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