【问题标题】:How to convert String data to int data for preparing linear regression?如何将 String 数据转换为 int 数据以准备线性回归?
【发布时间】:2022-01-24 01:28:43
【问题描述】:

我正在尝试准备我的数据以进行回归。所以我正在尝试使用此代码将字符串列转换为整数:

train["comment"] = train["comment"].astype(int)

但我收到此错误:

runfile('C:/Users/hayyi/.spyder-py3/temp.py', wdir='C:/Users/hayyi/.spyder-py3') Traceback(最近一次调用最后):

文件“C:\Users\hayyi.spyder-py3\temp.py”,第 57 行,在 train["comment"] = train["comment"].astype(int)

文件 "D:\SpyderUI\MiniConda\envs\spyder-env\lib\site-packages\pandas\core\generic.py", 第 5815 行,在 astype 中 new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors)

文件 "D:\SpyderUI\MiniConda\envs\spyder-env\lib\site-packages\pandas\core\internals\managers.py", 第 418 行,在 astype 中 return self.apply("astype", dtype=dtype, copy=copy, errors=errors)

文件 "D:\SpyderUI\MiniConda\envs\spyder-env\lib\site-packages\pandas\core\internals\managers.py", 第 327 行,申请中 应用 = getattr(b, f)(**kwargs)

文件 "D:\SpyderUI\MiniConda\envs\spyder-env\lib\site-packages\pandas\core\internals\blocks.py", 第 591 行,在 astype 中 new_values = astype_array_safe(values, dtype, copy=copy, errors=errors)

文件 "D:\SpyderUI\MiniConda\envs\spyder-env\lib\site-packages\pandas\core\dtypes\cast.py", 第 1309 行,在 astype_array_safe 中 new_values = astype_array(values, dtype, copy=copy)

文件 "D:\SpyderUI\MiniConda\envs\spyder-env\lib\site-packages\pandas\core\dtypes\cast.py", 第 1257 行,在 astype_array 中 values = astype_nansafe(values, dtype, copy=copy)

文件 "D:\SpyderUI\MiniConda\envs\spyder-env\lib\site-packages\pandas\core\dtypes\cast.py", 第 1174 行,在 astype_nansafe 中 return lib.astype_intsafe(arr, dtype)

文件“pandas_libs\lib.pyx”,第 679 行,在 pandas._libs.lib.astype_intsafe

ValueError: int() 以 10 为底的无效文字:“他得到了他的 钱……现在他在等到两年后的选举…… 肮脏的政客需要再次害怕焦油和羽毛……但是 他们不是,所以人们被搞砸了。”

顺便说一句,我尝试了这个,但我得到了同样的错误:

train["comment"]=train["comment].str.replace(',','').astype(int)

还有一个问题,这种转换是准备字符串数据回归的正确方法吗?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    假设字符串值为字符串数据类型的数字,试试:

    train['comment']= pd.to_numeric(train['comment'], errors='coerce')
    

    如果列包含任何 NaN 值,请使用:

    train['comment']= pd.to_numeric(train['comment'], errors='coerce').fillna(0).astype(np.int64)
    

    【讨论】:

    • 啊,非常感谢。这解决了我的问题。现在我得到“输入包含 NaN、无穷大或对于 dtype('float64') 来说太大的值。”尝试回归时出错。你能告诉我为什么我会得到这个吗?
    • 当然,让我解决这个问题。
    • 检查更新的答案
    猜你喜欢
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2014-02-21
    • 1970-01-01
    • 2018-07-17
    相关资源
    最近更新 更多