python - 尝试将 Dataframe 列转换为 float 时出现 ValueError

标签 python pandas

我正在尝试将下面的数据框 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/

相关文章:

Python、Flask、Gunicorn 错误 : Unrecognized Arguments

python - 如果两列之间存在反向,Pandas 会删除重复项

python - 如何从带有列名和列值的 pandas DataFrame 生成列表?

python - Pandas 箱线图,子图中的不同 y 轴

python - 如何提高 python 数据帧中平均计算的性能

python - 如何并行化复杂的 for 循环

python - 如何获取所有 Jenkins 变量

python - 使用 Python 3 对数组进行排序

python - Pandas 中仅针对所有先前值的条件运行总和

python - 使用 itertools、melt 和 groupby 正确地使用 Pandas 计算每个属性值的事件对