繁体   English   中英

使用 Pandas 将 python 字符串转换为日期时出错

[英]Error with a python string to dateconversion using Pandas

我正在努力更改 dataframe 的日期格式。我收到以下错误:

ValueError:组装映射至少需要指定 [year, month, day]:缺少 [day,month,year]

那是我的代码,

price_spx = spx.history(start="2010-01-01", end="2019-07-16")

components = pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
spx_tickers = components[0]
spx_changes = components[1]

pd.to_datetime(spx_changes['Date'],format='%B %d, %Y')

谢谢你的帮助:) !

如果仔细查看spx_changes的样子,您会发现您有一个多级列索引(列名是元组):

spx_changes.info()
#<class 'pandas.core.frame.DataFrame'>
#RangeIndex: 297 entries, 0 to 296
#Data columns (total 6 columns):
# #   Column               Non-Null Count  Dtype 
#---  ------               --------------  ----- 
# 0   (Date, Date)         297 non-null    object
# 1   (Added, Ticker)      291 non-null    object
# 2   (Added, Security)    291 non-null    object
# 3   (Removed, Ticker)    285 non-null    object
# 4   (Removed, Security)  285 non-null    object
# 5   (Reason, Reason)     297 non-null    object
#dtypes: object(6)
#memory usage: 14.0+ KB

因此, spx_changes['Date']返回 DataFrame,因为只给出了一个级别。 pd.to_datetime()需要一系列值,而不是整个 DataFrame (实际上就像您编写pd.to_datetime(spx_changes, format="%B %d, %Y") ):

pd.to_datetime(spx_changes['Date', 'Date'], format='%B %D, %Y')

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM