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')
convert_objectscan handle empty stringsFAILUREstill keeps getting printed out.convert_objects, you just need to call it once, also when you claim it fails, after callingconvert_objectswhat doesdf.info()show? You may be getting what you think is an error because thedtypeis actuallynp.float64