【问题标题】:How to convert month name and year to datetime with pandas如何使用熊猫将月份名称和年份转换为日期时间
【发布时间】:2020-05-26 18:13:46
【问题描述】:

我正在尝试使用 pandas 将我的数据框的索引转换为日期时间对象,但一直收到此错误--

“ValueError: 时间数据 'Jan 20' 与格式 '%b, %y' 不匹配(匹配)”。

我仔细检查了日期时间格式并删除了连字符,但仍然没有运气。我怎样才能解决这个问题?

这是我尝试过的:

import pandas as pd

table = pd.read_html('https://www.finra.org/investors/learn-to-invest/advanced-investing/margin-statistics')

#set the index to date column
df = table[0].set_index('Month/Year')

df.index = df.index.str.replace("-", " ")

df.index = pd.to_datetime(df.index, format="%b, %y")

【问题讨论】:

    标签: python pandas dataframe datetime


    【解决方案1】:

    我想你有一个额外的逗号。这对我来说很好用:

    df.index = pd.to_datetime(df.index, format="%b %y")
    
    print(df.index)
    

    输出:

    DatetimeIndex(['2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01'], dtype='datetime64[ns]', name='Month/Year', freq=None)
    

    【讨论】:

      【解决方案2】:

      小改动:

      df.index = pd.to_datetime(df.index, format="%b-%y")
      print(df)
      
                  Debit Balances in Customers' Securities Margin Accounts  ...  Free Credit Balances in Customers' Securities Margin Accounts
      Month/Year                                                           ...
      2020-01-01                                             561812        ...                                             186847
      2020-02-01                                             545127        ...                                             197716
      2020-03-01                                             479291        ...                                             226202
      2020-04-01                                             524696        ...                                             217187
      
      [4 rows x 3 columns]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-21
        • 2018-12-21
        • 2018-12-24
        • 1970-01-01
        相关资源
        最近更新 更多