我正在尝试将下面的数据框 df
的列 Yield_pct
下的所有数据转换为浮点类型,但在执行此操作时遇到问题。我收到错误 ValueError: Could not conversion string to float: ' na'
因此我添加了行 if row1['Yield_pct'] != 'na':
到我的代码如下,但添加此行后出现相同的错误。
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')
谢谢
编辑:这是数据框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
我现在使用的代码:
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_objects
,它将把任何 duff 值强制转换为 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
关于python - 尝试将 Dataframe 列转换为 float 时出现 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31119313/