gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:11 25 4
gpt4 key购买 nike

我有一个名为 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

关于python - Pandas:根据 DataFrame 中的其他列在 DataFrame 中创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33609913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com