简体   繁体   English

ValueError:在 Python 中尝试将字符串转换为 Int 时,出现基数为 10 的 int() 的无效文字

[英]ValueError: invalid literal for int() with base 10 Shows up When Trying to Convert String into Int in Python

Im trying to setup my dataset for my linear regression.我试图为我的线性回归设置我的数据集。 I can't simply fit the dates in the LinReg model because it needs a numerical value or an int.我不能简单地将日期放入 LinReg model 中,因为它需要一个数值或一个整数。 So Im trying to use int() to convert the string into int.所以我尝试使用int()将字符串转换为 int。 But I get an error - ValueError: invalid literal for int() with base 10但我收到一个错误 - ValueError: invalid literal for int() with base 10

The code:编码:

df = pd.read_csv('data/Customers.csv')

print(int(df.date[0]))

Try parsing date as Timestamp and using toordinal on that:尝试将日期解析为 Timestamp 并在其上使用 toordinal:

In [14]: import io, pandas as pd
    ...: 
    ...: text = "date\n01/31/2021\n"
    ...: buff = io.StringIO(text)
    ...: df = pd.read_csv(buff, converters={"date": pd.Timestamp})
    ...: ts = df.date[0]

In [15]: ts
Out[15]: Timestamp('2021-01-31 00:00:00')

In [16]: ts.toordinal()
Out[16]: 737821

In [17]: 

Source :来源

datetime.toordinal() is a simple method used to manipulate the objects of DateTime class. datetime.toordinal() 是一种用于操作 DateTime class 对象的简单方法。 It returns proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. The function returns the ordinal value for the given DateTime object.它返回日期的预测公历序数,其中第 1 年的 1 月 1 日有序数 1。 function 返回给定日期时间 object 的序数值。

If January 1 of year 1 has ordinal number 1 then, January 2 year 1 will have ordinal number 2, and so on.如果第 1 年的 1 月 1 日的序号为 1,则第 1 年的 1 月 2 日的序号为 2,依此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:尝试将字符串转换为int,将以10为底的int()的int无效文字错误转换为int无效文本 - Python: Trying to convert string to int, get error to int invalid literal for int() with base 10: '' ValueError:int() 的无效文字,基数为 10:'string' - ValueError: invalid literal for int() with base 10: 'string' ValueError:int() 的无效文字以 10 为基数:' ' 转换数据类型时 - ValueError: invalid literal for int() with base 10: ' ' when convert type of data ValueError:int()以10为底的无效文字:“-”(Python) - ValueError: invalid literal for int() with base 10: '-' (Python) (Python)ValueError:以10为底的int()的无效文字:'' - (Python) ValueError: invalid literal for int() with base 10: '' Python:ValueError:以10为底的int()的无效文字:“” - Python: ValueError: invalid literal for int() with base 10: '"' Python 3,ValueError:以10为底的int()无效文字: - Python 3, ValueError: invalid literal for int() with base 10: '' ValueError:以10为底的int()的无效文字:Python - ValueError: invalid literal for int() with base 10: Python Python ValueError:int()的基数为10的文字无效 - Python ValueError: invalid literal for int() with base 10 python:ValueError:以10为底的int()的无效文字:'' - python : ValueError: invalid literal for int() with base 10: ' '
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM