【问题标题】:How to remove square bracket from pandas dataframe将对象转换为浮点数 - NaN [重复]
【发布时间】:2021-12-18 16:07:24
【问题描述】:

我有一个包含几列的表格,其中数字显示为对象。我想将这种格式“[0.015158]”的对象转换为浮点数“0.015158”

我的代码是:

coeff_dfethapoly['Slope (b)_d1']= pd.to_numeric(coeff_dfethapoly['Slope (b)_d1'], errors = 'coerce')

此代码不起作用,结果为“NaN”。

【问题讨论】:

  • 您可能希望包含minimal reproducible example 以帮助人们重现您的问题。我怀疑解决方案很简单,但我不能确定,因为我无法用你不完整的代码重现问题。一些想法:(1)明确pd是什么; (2) 添加print 语句,显示相关对象的值。

标签: python pandas dataframe


【解决方案1】:

IIUC,您需要先从每个元素中删除 [] 然后转换为浮点数,您可以这样做:

# If you have this:
coeff_dfethapoly = pd.DataFrame({'Slope (b)_d1': ["[0.015158]"]})

coeff_dfethapoly['Slope (b)_d1'] = coeff_dfethapoly['Slope (b)_d1'].str[1:-1]
coeff_dfethapoly['Slope (b)_d1'] = pd.to_numeric(coeff_dfethapoly['Slope (b)_d1'], errors = 'coerce')

输出:

>>> coeff_dfethapoly['Slope (b)_d1']
0    0.015158
Name: Slope (b)_d1, dtype: float64

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-20
    • 2021-08-11
    • 1970-01-01
    • 2021-05-24
    • 2021-06-18
    • 2018-04-30
    • 2012-05-09
    • 2020-08-14
    相关资源
    最近更新 更多