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

Joa*_*iay 1 python datetime date pandas

我有这种包含 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
Run Code Online (Sandbox Code Playgroud)

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

10/2009
12/2009
4/2009
8/2007
7/2008
6/2009
1/2009
12/2007
9/2009
2/2006
3/2009
2/2007
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

我认为你可以先使用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'>
Run Code Online (Sandbox Code Playgroud)

或者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'>
Run Code Online (Sandbox Code Playgroud)

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'>
Run Code Online (Sandbox Code Playgroud)