【问题标题】:Python How to get 1st element of date tokenPython如何获取日期标记的第一个元素
【发布时间】:2014-08-02 04:47:27
【问题描述】:

我使用的是 Python 2.7,我的数据如下所示:

import pandas as pd            
df = pd.DataFrame({ 'DateVar' : ['9/1/2013', '10/1/2013', '2/1/2014'],
                'Field' : 'foo' })   

我想解析 DateVar 以创建 2 个新字段:一个“月”字段和一个“年”字段。

我能够通过矢量化字符串方法标记“DateVar”:

df.DateVar.str.split('/')

这有点接近我想要的,所以接下来我尝试使用以下代码对月份 [9, 10, 2] 进行切片:

df.DateVar.str.split('/')[0]

但出乎意料的是,我得到了:

['9', '1', '2013']

那么我怎样才能得到所有月份的向量呢?

【问题讨论】:

  • 使用map(int, df.DateVar.str.split('/')[0])将每个元素转换为整数?
  • 你想要什么确切的输出?

标签: python string date vector pandas


【解决方案1】:
v = [x[0] for x in df.DateVar.str.split('/')]

【讨论】:

    【解决方案2】:

    如果只需要一列,可以使用:

    df.DateVar.str.split("/").str[0]
    

    如果您需要月份和日期列,请使用str.extract

    import pandas as pd            
    df = pd.DataFrame({ 'DateVar' : ['9/1/2013', '10/1/2013', '2/1/2014'],
                    'Field' : 'foo' })   
    
    print df.DateVar.str.extract(r"(?P<month>\d+)/(?P<day>\d+)/\d+").astype(int)
    

    输出:

      month  day
    0      9    1
    1     10    1
    2      2    1
    

    【讨论】:

      【解决方案3】:

      因为

      >>> df.DateVar.str.split('/')
      0     [9, 1, 2013]
      1    [10, 1, 2013]
      2     [2, 1, 2014]
      

      所以

      >>> df.DateVar.str.split('/')[0]
      ['9', '1', '2013']
      

      【讨论】:

        猜你喜欢
        • 2022-06-14
        • 2017-03-07
        • 2019-09-25
        • 2012-06-22
        • 2014-09-08
        • 1970-01-01
        • 2013-04-29
        • 1970-01-01
        • 2011-07-10
        相关资源
        最近更新 更多