【问题标题】:converting object types columns into numeric type using pandas使用 pandas 将对象类型列转换为数字类型
【发布时间】:2018-06-25 01:16:13
【问题描述】:

我正在尝试使用 pandas 清理数据。当我执行 df.datatypes 时,它显示列是对象类型。我希望将它们转换为数字类型。 我尝试了各种方法;

data[['a','b']] = data[['a','b']].apply(pd.to_numeric, errors ='ignore')

那么,

data['c'] = data['c'].infer_objects()

但似乎没有任何效果。解释器不会抛出任何错误,但同时也不会执行所需的转换。

任何帮助将不胜感激。

提前致谢。

【问题讨论】:

  • 你的数据怎么样,你想要的转化率是多少?当前输出是多少?
  • @AkshayNevrekar 是的尝试但没有转换
  • 您是否将值分配给df['col']=df['col'].astype('int') 之类的列?
  • @Dark Data 在 Excel 工作表中,列有字符串和整数值,包括正数和负数。列类型是对象,我希望拥有数字类型
  • @AkshayNevrekar 我给出错误提示 ValueError: invalid literal for int() with base 10: '-'

标签: python pandas data-cleaning


【解决方案1】:

to_numeric的帮助页面,errors的描述如下:

errors : {'ignore', 'raise', 'coerce'}, default 'raise'
        - If 'raise', then invalid parsing will raise an exception
        - If 'coerce', then invalid parsing will be set as NaN
        - If 'ignore', then invalid parsing will return the input

如果您的apply 返回您的输入而不对其进行任何操作,那么原因是因为您有不可转换的对象,并且使用errors='ignore' 调用to_numeric 没有帮助。

尝试使用第二个选项,errors='coerce'

df = df.apply(pd.to_numeric, errors='coerce')

或者,

for c in df.columns:
    df[c] = pd.to_numeric(df[c], errors='coerce')

另外,infer_objects 执行软类型转换。如果要检查列 dtypes,请改用 df.dtypes

【讨论】:

  • @Dark 感谢提醒,这是一个错字!
  • 这可能是它。很想知道 OP 得到了什么
  • for c in ['a', 'b']: df[c] = pd.to_numeric(df[c], errors='coerce') 这仅适用于少数列。对于其余列,dtypes 是 object
  • @DhvaniShah 这意味着您没有遍历所有这些列。呃,试试for c in df.columns: df[c] = pd.to_numeric(df[c], errors='coerce')
  • 没有。我确实迭代了列列表,但它只对 3 列执行了转换。
猜你喜欢
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 2021-08-11
  • 2018-11-08
  • 2018-11-27
  • 2016-11-14
  • 1970-01-01
  • 2019-10-11
相关资源
最近更新 更多