代码之家  ›  专栏  ›  技术社区  ›  Marco

pd.to_datetime 不尊重格式

  •  1
  • Marco  · 技术社区  · 7 年前

    我有以下数据帧:

        month     value
    0   1949-01    3
    1   1949-02    4
    2   1949-03    5
    
    df['month'] = pd.to_datetime(df['month'], format= '%Y/%m')
    

    我想以以下格式获取月份:

     1949/01
    

    但输出总是这样:

       month        value
    0   1949-01-01    3
    1   1949-02-01    4
    2   1949-03-01    5
    

    为什么它会自动添加日期而不遵守格式?

    2 回复  |  直到 7 年前
        1
  •  3
  •   dennissv    7 年前

    这就是datetime使用的格式。如果需要,可以使用 dt.strftime

    df['month'] = df['month'].dt.strftime('%Y/%m')
    

    或者,您可以从一个更简单的方法开始,简单地使用映射函数,无需涉及日期时间格式

    df['month'] = df['month'].map(lambda x: x.replace('-', '/'))
    
        2
  •  1
  •   Tom Johnson    7 年前

    import pandas as pd
    
    # create sample dataframe where month is a string
    df = pd.DataFrame({'month_str':['1949-01', '1949-02', '1949-03']})
    
    # now create a new column where you have converted the string to a datetime
    df['month_datetime'] = pd.to_datetime(df['month_str'])
    
    # now convert the datetime back to a string with your desired format
    df['month_new_str'] = df['month_datetime'].dt.strftime('%Y/%m')
    
    # skip all the fooling around with datetimes and just manipulate it as a string directly
    
    df['month_new_str2'] = df['month_str'].apply(lambda x: x.replace('-', '/'))
    
    print(df.dtypes)
    print(df)
    

    这将产生以下输出:

    month_str                 object
    month_datetime    datetime64[ns]
    month_new_str             object
    month_new_str2            object
    dtype: object
      month_str month_datetime month_new_str month_new_str2
    0   1949-01     1949-01-01       1949/01        1949/01
    1   1949-02     1949-02-01       1949/02        1949/02
    2   1949-03     1949-03-01       1949/03        1949/03
    

    注意,原来的'month\u str'列有一个object的数据类型(它是一个字符串)。当您调用\u datetime时,我们将其转换为datetime类型(不需要指定格式,pandas会计算出来)。但是当显示时,pandas将它显示为一个完整的日期(这就是为什么你会看到day字段)。正如@sds所指出的,如果您只是想将破折号切换为斜杠,那么您只需操纵原始字符串来生成一个新字符串(“month\u new\u str2”)。