Search code examples
pythonpandastype-conversiondata-analysis

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.


Solution

  • 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)