我覺得你可以先用to_datetime
然後to_period
:
df.col = pd.to_datetime(df.col).dt.to_period('m')
print (df)
col
0 2009-10
1 2009-12
2 2009-04
3 2007-08
4 2008-07
5 2009-06
6 2009-01
7 2007-12
8 2009-09
9 2006-02
10 2009-03
11 2007-02
print (type(df.loc[0,'col']))
<class 'pandas._period.Period'>
或者strftime
:
df.col = pd.to_datetime(df.col).dt.strftime('%m/%Y')
print (df)
col
0 10/2009
1 12/2009
2 04/2009
3 08/2007
4 07/2008
5 06/2009
6 01/2009
7 12/2007
8 09/2009
9 02/2006
10 03/2009
11 02/2007
print (type(df.loc[0,'col']))
<class 'str'>
或者replace
通過regex
:
df.col = df.col.str.replace('/.+/','/')
print (df)
col
0 10/2009
1 12/2009
2 4/2009
3 8/2007
4 7/2008
5 6/2009
6 1/2009
7 12/2007
8 9/2009
9 2/2006
10 3/2009
11 2/2007
print (type(df.loc[0,'col']))
<class 'str'>
你可以用正則表達式're.sub('/。+ /','/','10/30/2009')'=> ''10/2009'' – Richy