Home > Enterprise >  Using astype() to convert string to number
Using astype() to convert string to number

Time:02-18

For the following simple dataframe

data = {'Name':['ww', 'xx'],
        'v1':[19968,5.83],
        'v2':[39936,11.31],
        'v3':[79872,19.26]}
df = pd.DataFrame(data)

where df looks like

  Name        v1        v2        v3
0   ww  19968.00  39936.00  79872.00
1   xx      5.83     11.31     19.26

when I use x = df.iloc[1,:].astype(float), I get this error

could not convert string to float: 'xx'

I expect to convert the row 1 to have: x = [5.83 11.31 19.26]

How can I fix it?

CodePudding user response:

You sliced the rows here and took all columns (thus the error as the first column contains strings).

You should rather slice both the rows and columns (to get rid of the first):

df.iloc[1,1:].astype(float)

or, explicitly select the number-only columns:

df.select_dtypes('number').iloc[1].astype(float)

output:

v1     5.83
v2    11.31
v3    19.26
Name: 1, dtype: float64
  • Related