Skip to main content
 首页 » 编程设计

python之Pandas:根据 DataFrame 中的其他列在 DataFrame 中创建新列

2024年10月24日9dflying

我有一个名为 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 是一个系列,而字符串函数不适用于系列。

请您参考如下方法:

使用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