簡體   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