【问题标题】:I am trying to convert an object type column to float. Not working我正在尝试将对象类型列转换为浮点数。不工作
【发布时间】:2023-04-09 12:58:02
【问题描述】:
TSRdfr["Return"] = pd.to_numeric(TSRdfr.Return, errors='coerce')

这不会将 Return 的数据类型从 Object 转换为 float64。我尝试删除 errors ='coerce' 以查看发生了什么。

我收到一条错误消息:

无法解析位置 0 处的 NaN

当我不使用errors = 'coerce'时。

从 Refinitiv Eikon API 访问退货编号。我假设它们太大而无法转换为float64。有什么建议吗??

【问题讨论】:

  • 你能提供更多关于TSRdfr的信息吗?内容是什么?
  • @bubble 我有一个数据框 TSRdfr,我已从 Python 上的 Eikon API 访问它。指数工具总回报 1. RIO.L. 15.990065 2. AAP.A. 22.543209 等等....
  • 总回报是对象类型
  • 我有一个数据框 TSRdfr,我已从 Python 上的 Eikon API 访问它。指数工具总回报 1. RIO.L. 15.990065 2. AAP.A. 22.543209 等等.... Total Return 的数据类型是我需要转换为 float64 的 Object。我正在使用下面的语法。 TSRdfr["总回报"] = pd.to_numeric(TSRdfr["总回报"], errors='coerce')

标签: python thomson-reuters-eikon refinitiv-eikon-api


【解决方案1】:

尝试以下方法:

import pandas as pd
import re
repat = re.compile('\d+(?:\.\d+)?')

# sample data frame 
df = pd.DataFrame({'Return': ['some data 123.123', 'tick 0.12']})

df.loc[:, 'Converted'] = df.Return.apply(lambda x: float(repat.findall(x)[0]))

希望有帮助

【讨论】:

  • import re repat = re.compile('\d+(?:\.\d+)?') TSR_df_06_09.loc[:, 'Converted'] = TSR_df_06_09.Return.apply(lambda x:浮动(repat.findall(x)[0]))
  • AttributeError: 'DataFrame' 对象没有属性 'Return'
  • 这意味着TSR_df_06_09 没有名为Return 的列。 TSR_df_06_09 的列名是什么?打印TSR_df_06_09.columns 以查看数据框的所有列。
【解决方案2】:

如果你的数字太大,可以使用十进制库

import decimal
decimal.getcontext().prec = 100
df[col] = df[col].map(lambda x: decimal.Decimal(x))

【讨论】:

  • import decimal decimal.getcontext().prec = 100 TSR_df_06_09['Total Return'] = pd.to_numeric(TSR_df_06_09['Total Return'].map(lambda x: decimal.Decimal(x) ))
  • 试过上面的代码..得到这个错误:InvalidOperation: []
猜你喜欢
  • 1970-01-01
  • 2022-11-21
  • 2018-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-03
  • 2019-06-13
相关资源
最近更新 更多