user131983
user131983

Reputation: 3927

ValueError when trying to convert Dataframe Column into float

I am trying to convert all the data under the Column Yield_pct of my dataframe df below into float types, but am facing issues doing this. I get the Error ValueError: could not convert string to float: ' na' and hence I added the line if row1['Yield_pct'] != 'na': to my code below, yet I get the same error after adding this line.

              Date      Maturity      Yield_pct Currency
0       1986-01-01          0.25             na      CAD
1       1986-01-02          0.25   0.0948511020      CAD
2       1986-01-03          0.25   0.0972953210      CAD
3       1986-01-06          0.25   0.0965403640      CAD
4       1986-01-07          0.25   0.0953292440      CAD


for (i1, row1) in (df.iterrows()):
    if row1['Yield_pct'] != 'na':
        row1['Yield_pct'] = float(row1['Yield_pct'])
        if isinstance(row1['Yield_pct'], float)==1:
            print('SUCCESS')
        else:
            print('FAILURE')

Thank You

Edit: This is the lower part of the dataframe df:

920538  2015-01-19  empty string                     CAD
920539  2015-01-20  empty string                     CAD
920540  2015-01-21  empty string                     CAD
920541  2015-01-22  empty string                     CAD
920542  2015-01-23  empty string                     CAD
920543  2015-01-26  empty string                     CAD

Code that I am now using:

df = update('CAD')[0]
for (i1, row1) in (df.iterrows()):
    df = df.convert_objects(convert_numeric=True)
    if isinstance(row1['Yield_pct'], float)==1:
        print('SUCCESS')
    else:
        print('FAILURE')

Upvotes: 2

Views: 7726

Answers (1)

EdChum
EdChum

Reputation: 393933

Just use convert_objects, it will coerce any duff values into NaN:

In [75]:
df = df.convert_objects(convert_numeric=True)
df

Out[75]:
         Date  Maturity  Yield_pct Currency
0  1986-01-01      0.25        NaN      CAD
1  1986-01-02      0.25   0.094851      CAD
2  1986-01-03      0.25   0.097295      CAD
3  1986-01-06      0.25   0.096540      CAD
4  1986-01-07      0.25   0.095329      CAD

Upvotes: 3

Related Questions