Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

converting feet-inch string DataFrame column to centimeters

I have a column of basketball players height:

0       6-10
1        6-9
2        7-2
3        6-1
4        6-6
        ... 
4545    6-11
4546     7-1
4547     6-1
4548     7-1
4549     6-3

I want to convert the values from feet to cm.
I made a split: player_data['height'].str.split('-'), and received a Series of arrays with separate feet and inches:

0       [6, 10]
1        [6, 9]
2        [7, 2]
3        [6, 1]
4        [6, 6]
         ...   
4545    [6, 11]
4546     [7, 1]
4547     [6, 1]
4548     [7, 1]
4549     [6, 3]

Now I try to convert values to float:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df = player_data['height'].str.split('-').astype(float)

But I receive an error: ValueError: setting an array element with a sequence.
What I’m doing wrong?

>Solution :

Assuming your end goal is to convert the "feet-inch" values to cm, I would do:

df['height_cm'] = (df['height'].str.extract('(\d*)-(\d*)')
                   .apply(pd.to_numeric, errors='coerce') # or .astype(int)
                   .mul([30.48, 2.54]).sum(axis=1)
                  )

Output:

     height  height_cm
0      6-10     208.28
1       6-9     205.74
2       7-2     218.44
3       6-1     185.42
4       6-6     198.12
4545   6-11     210.82
4546    7-1     215.90
4547    6-1     185.42
4548    7-1     215.90
4549    6-3     190.50
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading