【问题标题】:pd.to_datetime giving jumbled datespd.to_datetime 给出混乱的日期
【发布时间】:2020-06-16 17:03:25
【问题描述】:

当我将时间序列日期分配为 datetimeindex 时,我的时间序列日期是混乱的(日/月)。奇怪的是解析器可能会出错,但尝试声明格式并使用 Dayfirst 但没有任何效果。

#input_data = pd.read_csv(url)
input_data = pd.read_csv(url,usecols=['Dates','TYAFWD Comdty'],skiprows=None, parse_dates=True, nrows=1500)

# Set Date as Index, clean dataframe
input_data = input_data.set_index('Dates')
df = pd.DataFrame(input_data).dropna()
print(df.columns)

# Create new Date index
data_time = pd.to_datetime(df.index)
datetime_index = pd.DatetimeIndex(data_time.values) 
df = df.set_index(datetime_index)
df.index = pd.to_datetime(df.index, infer_datetime_format='%Y/%m/%d' )


df['year'] = pd.DatetimeIndex(df.index).year
df['month'] = pd.DatetimeIndex(df.index).month
df['week'] = pd.DatetimeIndex(df.index).weekofyear
print(df.head(30))

从输出中可以看出这一切都搞混了。 我希望输出中的所有条目都在 5 月,即第 5 个月,但它会将日期翻转一次

这是我的原始数据: https://raw.githubusercontent.com/esheehan1/projects/master/BB_FUT_DATA.csv

Index(['TYAFWD Comdty'], dtype='object')
            TYAFWD Comdty  year  month  week
2020-05-26          0.508  2020      5    22
2020-05-25          0.494  2020      5    22
2020-05-22          0.494  2020      5    21
2020-05-21          0.508  2020      5    21
2020-05-20          0.512  2020      5    21
2020-05-19          0.512  2020      5    21
2020-05-18          0.552  2020      5    21
2020-05-15          0.483  2020      5    20
2020-05-14          0.474  2020      5    20
2020-05-13          0.494  2020      5    20
2020-12-05          0.510  2020     12    49
2020-11-05          0.548  2020     11    45
2020-08-05          0.527  2020      8    32
2020-07-05          0.494  2020      7    27
2020-06-05          0.568  2020      6    23
2020-05-05          0.541  2020      5    19

【问题讨论】:

标签: pandas


【解决方案1】:

在编写代码对其进行操作之前,先查看一些原始数据总是一个好主意(如果可以的话)。

在您的特定情况下,日期格式为 D/M/Y,这是国际和欧洲标准。 pd.read_csv 函数默认使用美国日期格式 M/D/Y。

使用参数dayfirst=True 改变它会得到你想要的输出。另外,我还稍微缩短了您的代码:

import pandas as pd
from datetime import date
url = 'https://raw.githubusercontent.com/esheehan1/projects/master/BB_FUT_DATA.csv'
df = pd.read_csv(url, usecols=['Dates','TYAFWD Comdty'], index_col=['Dates'], skiprows=None, parse_dates=True, dayfirst=True, nrows=1500)
print(df.iloc[15:20,:])

            TYAFWD Comdty
Dates                    
2020-05-05          0.541
2020-05-04          0.527
2020-05-01          0.512
2020-04-30          0.528
2020-04-29          0.521

添加您想要的列:

df['year']  = pd.to_datetime(df.index).year
df['month'] = pd.to_datetime(df.index).month
df['week']  = pd.to_datetime(df.index).weekofyear
print(df.iloc[15:20,:])

            TYAFWD Comdty  year  month  week
Dates                                       
2020-05-05          0.541  2020      5    19
2020-05-04          0.527  2020      5    19
2020-05-01          0.512  2020      5    18
2020-04-30          0.528  2020      4    18
2020-04-29          0.521  2020      4    18

查看pandas documentation 的 pd.read_csv 有很多参数可能对您有用!

【讨论】:

    【解决方案2】:

    我看不出你的输出有什么问题。

    似乎是.to_datetime() 的默认行为。它默认按降序排列yearmonthday。这是“标准”。

    但是,如果您想确保正确转换数据,请使用参数format

    df.index = df.index.to_datetime(format='%d/%m/%Y')
    # that's it
    

    【讨论】:

      【解决方案3】:

      pd.read_csv 中的默认日期时间格式会导致您的问题,因为它假定/ 分隔的格式是%m/%d/%Y。我还建议您稍微简化一下代码,因为目前有很多不必要的强制转换操作:

      import pandas as pd
      
      # Result is a DataFrame already
      df = pd.read_csv('BB_FUT_DATA.csv', usecols=['Dates', 'TYAFWD Comdty'], skiprows=None, nrows=1500)
      df.dropna(inplace=True)
      df.Dates = pd.to_datetime(df.Dates, format='%d/%m/%Y')
      df.set_index('Dates', inplace=True)
      # Since df.index is already of type datetime you can access the year, month, weekofyear attributes directly
      df['year'] = df.index.year
      df['month'] = df.index.month
      df['week'] = df.index.weekofyear
      print(df.head(30))
      

      或者,您可以在pd.read_csv 中使用dayfirst=True(正如@eNc 指出的那样)或date_parser=lambda x: pd.to_datetime(x, format='%d/%m/%Y')na_filter 来完全执行此操作,以删除具有NaN 和NA 值的行:

      import pandas as pd
      
      
      df = pd.read_csv(
          'BB_FUT_DATA.csv',
          usecols=['Dates', 'TYAFWD Comdty'],
          parse_dates=True,
          dayfirst=True,
          skiprows=None,
          nrows=1500,
          index_col='Dates',
          na_filter=True
          )
      df['year'] = df.index.year
      df['month'] = df.index.month
      df['week'] = df.index.weekofyear
      print(df.head(30))
      

      输出:

                  TYAFWD Comdty  year  month  week
      Dates                                       
      2020-05-26          0.508  2020      5    22
      2020-05-25          0.494  2020      5    22
      2020-05-22          0.494  2020      5    21
      2020-05-21          0.508  2020      5    21
      2020-05-20          0.512  2020      5    21
      2020-05-19          0.512  2020      5    21
      2020-05-18          0.552  2020      5    21
      2020-05-15          0.483  2020      5    20
      2020-05-14          0.474  2020      5    20
      2020-05-13          0.494  2020      5    20
      2020-05-12          0.510  2020      5    20
      2020-05-11          0.548  2020      5    20
      2020-05-08          0.527  2020      5    19
      2020-05-07          0.494  2020      5    19
      2020-05-06          0.568  2020      5    19
      2020-05-05          0.541  2020      5    19
      2020-05-04          0.527  2020      5    19
      2020-05-01          0.512  2020      5    18
      2020-04-30          0.528  2020      4    18
      2020-04-29          0.521  2020      4    18
      2020-04-28          0.519  2020      4    18
      2020-04-27          0.559  2020      4    18
      2020-04-24          0.518  2020      4    17
      2020-04-23          0.512  2020      4    17
      2020-04-22          0.514  2020      4    17
      2020-04-21          0.474  2020      4    17
      2020-04-20          0.490  2020      4    17
      2020-04-17          0.521  2020      4    16
      2020-04-16          0.510  2020      4    16
      2020-04-15          0.498  2020      4    16
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-22
        • 2020-11-17
        • 1970-01-01
        • 2022-01-14
        • 2021-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多