gpt4 book ai didi

python - 日期时间行为类型错误: parser() missing 1 required positional argument:

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:42 28 4
gpt4 key购买 nike

我已经修改了

def parser(x):
return datetime.strptime('190'+x, '%Y-%m')

因为我的每月日期是从 2002 年到 2017 年

def parser(x,y):
return datetime.strptime('20'+x+y, '%Y-%m')

当我运行时

s = read_csv('output.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)

终端输出显示

site-packages/pandas/io/parsers.py", line 3030, in converter
date_parser(*date_cols), errors='ignore')
TypeError: parser() missing 1 required positional argument: 'y'

还有

miniconda3/lib/python3.6/site-packages/pandas/io/parsers.py", line 3039, in converter
dayfirst=dayfirst),
File "pandas/_libs/tslibs/parsing.pyx", line 434, in pandas._libs.tslibs.parsing.try_parse_dates
File "pandas/_libs/tslibs/parsing.pyx", line 431, in pandas._libs.tslibs.parsing.try_parse_dates
TypeError: parser() missing 1 required positional argument: 'y'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "a212.py", line 8, in <module>
series = read_csv('output.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)

位置参数有问题。我应该更改什么?编辑

如果我尝试使用一个参数,它就不起作用

line 362, in _strptime
(data_string, format))
ValueError: time data '202002-01-15' does not match format '%Y-%m'

数据

Date, Price 
2002-01-15,3.1
2002-02-15,2.86
2002-03-15,3.37
2002-04-15,3.8
2002-05-15,3.78
2002-06-15,3.61
2002-07-15,3.49
2002-08-15,3.42
2002-09-15,3.71
2002-10-15,4.19
2002-11-15,4.35

最佳答案

pandas.read_csv 的文档状态:

date_parser : function, default None

Function to use for converting a sequence of string columns to an array of datetime instances. The default uses dateutil.parser.parser to do the conversion. Pandas will try to call date_parser in three different ways, advancing to the next if an exception occurs: 1) Pass one or more arrays (as defined by parse_dates) as arguments; 2) concatenate (row-wise) the string values from the columns defined by parse_dates into a single array and pass that; and 3) call date_parser once for each row using one or more strings (corresponding to the columns defined by parse_dates) as arguments.

当数组(您的例子中的第一列)作为参数传递时,您的解析器函数将应用于该列中的每个值。

换句话说,只有一个参数将被传递给您的函数。但您的函数需要 2 个参数(xy)。

您需要准确地弄清楚要对列中的字符串应用什么逻辑,并以 f(x) 的形式应用它。

鉴于您提供的数据,这应该足够了:

from datetime import datetime

def parser(x):
return datetime.strptime(x, '%Y-%m-%d')

s = pd.Series(['2002-01-15', '2002-02-15', '2002-03-15'])
s.apply(parser)

# 0 2002-01-15
# 1 2002-02-15
# 2 2002-03-15
# dtype: datetime64[ns]

关于python - 日期时间行为类型错误: parser() missing 1 required positional argument:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48841370/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com