gpt4 book ai didi

python - 如何从 Pandas 的 YYYY-YY 格式列中提取去年 (YYYY)

转载 作者:行者123 更新时间:2023-12-02 15:53:19 31 4
gpt4 key购买 nike

我正在尝试以 YYYY-YY 格式提取会计日期字符串的最后一年 (YY)。例如,这个“1999-00”的最后一年是 2000 年。

当前代码似乎涵盖了除此之外的大多数情况。

import pandas as pd
import numpy as np


test_df = pd.DataFrame(data={'Season':['1996-97', '1997-98', '1998-99',
'1999-00', '2000-01', '2001-02',
'2002-03','2003-04','2004-05',
'2005-06','2006-07','2007-08',
'2008-09', '2009-10', '2010-11', '2011-12'],
'Height':np.random.randint(20, size=16),
'Weight':np.random.randint(40, size=16)})

我需要一个逻辑来包括一个情况,如果是世纪末,那么我的应用方法应该添加到前两位数字,我相信这是我唯一缺少的情况。

当前代码如下:

test_df['Season'] = test_df['Season'].apply(lambda x: x[0:2] + x[5:7])

最佳答案

这也应该有效:

pd.to_numeric(test_df['Season'].str.split('-').str[0]) + 1

输出:

0     1997
1 1998
2 1999
3 2000
4 2001
5 2002
6 2003
7 2004
8 2005
9 2006
10 2007
11 2008
12 2009
13 2010
14 2011
15 2012

关于python - 如何从 Pandas 的 YYYY-YY 格式列中提取去年 (YYYY),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71879050/

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