gpt4 book ai didi

python - 如何从每行的字符串中提取年份并用这些年份生成新行

转载 作者:行者123 更新时间:2023-12-01 00:29:40 24 4
gpt4 key购买 nike

我有一个如下所示的数据框。

df = pd.DataFrame({'business_id':["a","b","c"], 
'time':['2016-04-26 19:49:16, 2016-08-30 18:36:57, 2016-11-18 01:54:50, 2017-04-20 18:39:06',
'2017-03-12 17:47:20, 2018-09-10 16:40:17',
'2014-02-28 12:11:16, 2019-05-30 18:36:57, 2019-07-20 04:54:28'] })

这是由上述代码生成的输入。


business_id time
a '2016-04-26 19:49:16, 2016-08-30 18:36:57, 2016-11-18 01:54:50, 2017-04-20 18:39:06'
b '2017-03-12 17:47:20, 2018-09-10 16:40:17'
c '2014-02-28 12:11:16, 2019-05-30 18:36:57, 2019-07-20 04:54:28'

下面是我想要生成的输出。

business_id                year
a 2016
a 2016
a 2016
a 2017
b 2017
b 2018
c 2014
c 2019
c 2019

我应该怎么做?

最佳答案

如果您只需要年份和 ID:

df[['business_id']].merge(df['time'].str
.extractall('(?P<year>\d{4})-')
.reset_index(1,drop=True),
left_index=True,
right_index=True)

输出:

  business_id  year
0 a 2016
0 a 2016
0 a 2016
0 a 2017
1 b 2017
1 b 2018
2 c 2014
2 c 2019
2 c 2019

关于python - 如何从每行的字符串中提取年份并用这些年份生成新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58275018/

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