Let’s say I have the following pandas df:
JavaScript
x
10
10
1
a = [['a', 0.1], ['b', ' 0.2'], ['c', '0.2,0.3']]
2
df = pd.DataFrame(a, columns= ['alphabet', 'floats'])
3
4
5
>>> df
6
alphabet floats
7
0 a 0.1
8
1 b 0.2
9
2 c 0.2,0.3
10
And I wish to remove all rows in which the value of the column floats cannot be cast as float and cast all values as float that can be cast as such:
JavaScript
1
5
1
>>> df
2
alphabet floats
3
0 a 0.1
4
1 b 0.2
5
Advertisement
Answer
use to_numeric()
+dropna()
:
JavaScript
1
2
1
df=df.assign(floats=pd.to_numeric(df['floats'],errors='coerce')).dropna(subset=['floats'])
2
OR in 2 steps:
JavaScript
1
3
1
df['floats']=pd.to_numeric(df['floats'],errors='coerce')
2
df=df.dropna(subset=['floats'])
3
output:
JavaScript
1
4
1
alphabet floats
2
0 a 0.1
3
1 b 0.2
4