【问题标题】:Convert month,day,year to month,year with python/pandas?使用 python/pandas 将月、日、年转换为月、年?
【发布时间】:2017-04-06 06:34:10
【问题描述】:

我有这种包含 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

【问题讨论】:

  • 你可以用正则表达式re.sub('/.+/','/', '10/30/2009') => '10/2009'

标签: python date datetime pandas


【解决方案1】:

我认为你可以先使用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'>

replaceregex

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

【讨论】:

  • 谢谢你,在我看来最好的选择和更优雅的是你说的第一个。 @jezrael
  • 如果我想知道最小日期(2007-02)和最大日期(2009-12),我该怎么做?
  • 使用print (df.col.max())print (df.col.min())
  • 我在评论之前尝试过但不起作用,它给了我一个错误: AttributeError: 'DataFrame' object has no attribute 'date' 。我的 col 叫“日期”。
  • 我认为需要[]print (df['col'].max())。我认为date 在熊猫中是method,所以出错了。但这很完美print (df['date'].max())
【解决方案2】:

您可以使用str.split 来构建字符串:

In [32]:
df['date'] =df['date'].str.split('/').str[0] + '/'  + df['date'].str.split('/').str[-1]
df

Out[32]:
       date
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

【讨论】:

    【解决方案3】:

    如果您更喜欢这种解决方案,也可以使用正则表达式。这将解决您的问题:

    import re
    
    res = re.sub(r"/\d\d?/", "/", s)
    

    (注意s 是日期字符串,可以是单独的日期字符串,也可以是包含所有日期的长字符串,并且您的结果绑定到res。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      相关资源
      最近更新 更多