Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Column Value in Pandas

I have a column 'Height' in Dataset as below.

      Height
0       6-2
1       6-6
2       6-5
3       6-5
4      6-10
5       6-9
6       6-8
7       7-0

and it's type is dtype: object Now I want to convert it into float i.e 6.2, 6.6 I tried with replace method but it didn't work. Can you suggest me how to do it? I am new to Pandas.

like image 718
Subham Avatar asked Jun 14 '26 12:06

Subham


2 Answers

Use Series.str.replace for replace substrings and convert to floats by :

df['Height'] = df['Height'].str.replace('-','.').astype(float)

Or use Series.replace with regex=True for replace substrings:

df['Height'] = df['Height'].replace('-','.', regex=True).astype(float)
like image 173
jezrael Avatar answered Jun 17 '26 01:06

jezrael


You can map the column with a lambda function to change it.

df.loc[:,'Height'] = df.loc[:,'Height'].map(lambda x: float(str(x).replace('-','.')))

I don't know your use case though, but if that's inches be careful.

like image 30
krewsayder Avatar answered Jun 17 '26 00:06

krewsayder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!