Skip to main content
 首页 » 编程设计

python之使用 python/pandas 将月、日、年转换为月、年

2025年05月04日25tuyile006

我有这种包含 9000 行的字符串列表,其中每行是月/日/年:

10/30/2009 
12/19/2009 
4/13/2009 
8/18/2007 
7/17/2008 
6/16/2009 
1/14/2009 
12/18/2007 
9/14/2009 
2/13/2006 
3/25/2009 
2/23/2007 

我想转换它,如果可能的话,只有月/年列表作为日期格式,如下所示:

10/2009 
12/2009 
4/2009 
8/2007 
7/2008 
6/2009 
1/2009 
12/2007 
9/2009 
2/2006 
3/2009 
2/2007 

请您参考如下方法:

我觉得你可以先用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通过正则表达式:

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'>