【问题标题】:How to convert negative string to integer in pandas?(how to handle "-") [duplicate]如何在熊猫中将负字符串转换为整数?(如何处理“-”)[重复]
【发布时间】:2016-01-21 02:00:02
【问题描述】:

这是我的问题:我在pandas.dataFrame 中有一列数字。但是有些数字需要转换,因为它们可能是string 的。

这是该列当前的外观:

[1
 -1,650.00
 -3
 ...]

我希望它都是整数。我的代码是:

df['columnname'].astype(int)

但是,当我将 -1,650.00 转换为 integer 时,我遇到了错误。即使代码是

df['columnname'].astype(float)
df['columnname'].astype(int)

它仍然没有解决问题。上面写着could not convert string to float: -,但“-”仍未处理。

【问题讨论】:

  • 这是因为逗号。用replace(',','') 之类的东西删除逗号,它应该可以工作
  • 你是如何创建 df 的?
  • 在 Python 中将带逗号的字符串转换为数字已在此处讨论:stackoverflow.com/questions/1779288/…

标签: python string pandas int


【解决方案1】:

试试这个:

df['columnname'].replace(',','').astype(float) 

或者:

float(df['columnname'].replace(',',''))

【讨论】:

  • 感谢您的回答和编辑!我感谢您的帮助。但我的关键问题是“-”仍然存在。错误说:“无法将字符串转换为浮点数:-”。如果我想在这个号码中保留“-”,你知道我该怎么做吗?
  • 你试过print type(float('-1650.00'.replace(',',''))) 吗?它返回<type 'float'>。 @ShaoqingZhang
【解决方案2】:

浮点数使用点来分隔整数部分和小数部分,而不是逗号。您的矢量应该如下所示:

[1,
-1650.00,
-3,
]

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 2017-07-31
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2012-06-28
    相关资源
    最近更新 更多