我正在嘗試以 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)})
我需要一個邏輯來包含一個案例,如果是世紀末,那么我的 apply 方法應該添加到前兩位數字,我相信這是我唯一缺少的案例。
當前代碼如下:
test_df['Season'] = test_df['Season'].apply(lambda x: x[0:2] x[5:7])
uj5u.com熱心網友回復:
這也應該有效:
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
uj5u.com熱心網友回復:
您可以使用.str.extract提取前四位數字
df['Season'] = df['Season'].str.extract('^(\d{4})').astype(int).add(1)
Season Height Weight
0 1997 4 22
1 1998 18 4
2 1999 19 27
3 2000 7 10
4 2001 19 9
5 2002 18 31
6 2003 19 9
7 2004 18 29
8 2005 13 17
9 2006 13 30
10 2007 5 14
11 2008 15 3
12 2009 13 10
13 2010 15 8
14 2011 0 23
15 2012 2 38
uj5u.com熱心網友回復:
干得好!使用以下函式代替 lambda:
def get_season(string):
century = int(string[:2])
preyear = int(string[2:4])
postyear = int(string[5:7])
if postyear < preyear:
century = 1
# zfill is so that "1" becomes "01"
return str(century).zfill(2) str(postyear).zfill(2)
uj5u.com熱心網友回復:
我使用會計年度模塊。
import numpy as np
import pandas as pd
import fiscalyear as fy
...
test_df['Season'] = test_df['Season'].apply(lambda x : fy.FiscalYear(int(x[0:4]) 1).fiscal_year)
print(test_df)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/459848.html
