【问题标题】:Why a date assignments in a dataframe is not a date type?为什么数据框中的日期分配不是日期类型?
【发布时间】:2019-04-26 20:56:12
【问题描述】:

df_vol DataFrame 创建如下

df_vol = df.loc[:, 1].map(fd.retrieve_symbol_datetime).to_frame('maturity')
df_vol['date'] = df_vol.index.date

df_vol.head()
                           maturity        date
2018-11-01 11:31:53.023  2022-04-01  2018-11-01
2018-11-01 16:30:15.287  2022-04-01  2018-11-01
2018-11-01 10:23:06.779  2022-10-01  2018-11-01
2018-11-01 16:30:15.291  2022-10-01  2018-11-01
2018-11-01 11:30:56.251  2018-12-01  2018-11-01

进一步检查df_vol显示

df_vol.dtypes
maturity    category
date          object
dtype: object

我希望maturity 列是日期类型,因为它由fd.retrieve_symbol_datetime() 的内容填充,该函数返回pandas.datetime()。 此外,date 列是一个对象类型,尽管它从 index.date 获取值。

我对@9​​87654330@ 的类型很感兴趣,因为我最终想要有所作为

pd.eval("(df_vol.maturity - df_vol.date)")

retrieve_symbol_datetime()

def retrieve_symbol_datetime(future: str):
    """
    Retrieves the maturity date of a future whose format is of the form AAAMYY.

    Params
    -------
    future : string, of form 'AAAMYY'
        This format is for futures where 'AAA' is the string that identifies
        the symbol, 'M' is the character that identifies the month, and 'YY' is
        a two-digit number that identifies the year.

    Returns : pandas.datetime
        Returns the date of maturiry of the future's symbol.

    Example
    -------
    If future = 'DI1Z20', then it returnts a pandas.datetime(2020, 12, 01).

    """
    year = 2000 + int(future[4: 6])
    month = convert_letter_symbol_month(future[3: 4])
    return pd.datetime(year, month, 1).date()

【问题讨论】:

  • 了解“fd”对应的包会很有帮助。请包括相关的进口声明。似乎您正在执行显示数据帧 df 的内容的 df.head(),但您正在计算数据帧 df_vol。你想改用 df_vol.head() 吗?

标签: python pandas date


【解决方案1】:

categorical 列存在问题,一种可能的解决方案是对其进行分类,对于 date 使用 floor 删除时间:

df_vol['maturity'] = pd.to_datetime(df_vol['maturity'].astype(str))
df_vol['date'] = df_vol.index.floor('d')

df_vol['diff'] = (df_vol['maturity'] - df_vol['date']).dt.days
print (df_vol)
                          maturity       date  diff
2018-11-01 11:31:53.023 2022-04-01 2018-11-01  1247
2018-11-01 16:30:15.287 2022-04-01 2018-11-01  1247
2018-11-01 10:23:06.779 2022-10-01 2018-11-01  1430
2018-11-01 16:30:15.291 2022-10-01 2018-11-01  1430
2018-11-01 11:30:56.251 2018-12-01 2018-11-01    30

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 2012-01-04
    • 2022-01-01
    相关资源
    最近更新 更多