2014-06-12 104 views
0

我使用Python 2.7的第1個要素,我的數據是這樣的:Python中如何獲得最新令牌

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

那麼我怎樣才能得到所有月份的矢量?

+0

使用'地圖(INT,df.DateVar.str.split( '/')[0])'到每個元素轉換爲整數。 – Fabricator

+0

你想要什麼確切的輸出? –

回答

1

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

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 
0

這是因爲

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

所以

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