【问题标题】:Pandas: Create new column in DataFrame based on other column in DataFramePandas:基于 DataFrame 中的其他列在 DataFrame 中创建新列
【发布时间】:2016-02-10 03:29:24
【问题描述】:

我有一个名为 df 的 pandas DataFrame,其中包含以下数据:

Index    SourceDate
0        AUG_2013
1        SEP_2013
2        JAN_2012

我需要添加一个额外的列,将这些日期中的每一个转换为以下 ConvertedDate 列。此列的日期格式为 YYYY-MM-DD,日期始终为 01。

Index    SourceDate    ConvertedDate
0        AUG_2013      2013-08-01
1        SEP_2013      2013-09-01
2        JAN_2012      2012-01-01

我尝试这样做:

df['ConvertedDate'] = time.strptime(str.replace(str.rsplit(df.SourceDate,'_',1)[0],'_','-01-'),'%b-%d-%Y')

不幸的是,这不起作用,因为 df.SourceDate 是一个系列,字符串函数不适用于系列。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用to_datetime 并传递格式字符串:

    In [64]:
    df['ConvertedDate'] =pd.to_datetime(df['SourceDate'], format='%b_%Y')
    df
    
    Out[64]:
       Index SourceDate ConvertedDate
    0      0   AUG_2013    2013-08-01
    1      1   SEP_2013    2013-09-01
    2      2   JAN_2012    2012-01-01
    

    python日期时间格式字符串说明符可以在here找到

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多