簡體   English   中英

Python如何獲取日期令牌的第一個元素

[英]Python How to get 1st element of date token

我正在使用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']

那么如何獲得所有月份的向量?

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

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

這是因為

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

所以

>>> df.DateVar.str.split('/')[0]
['9', '1', '2013']
v = [x[0] for x in df.DateVar.str.split('/')]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM