2015-11-02 183 views
0
import pandas as pd 
import io 
import numpy as np 
import datetime 

data = """ 
    date   id 
    2015-10-31 50230 
    2015-10-31 48646 
    2015-10-31 48748 
    2015-10-31 46992 
    2015-11-01 46491 
    2015-11-01 45347 
    2015-11-01 45681 
    2015-11-01 46430 
    """ 

df = pd.read_csv(io.StringIO(data), delimiter='\s+', index_col=False, parse_dates = ['date']) 

df2 = pd.DataFrame(index=df.index) 

df2['Check'] = np.where(datetime.datetime.strftime(df['date'],'%B')=='October',0,1) 

我有我正在使用的這個示例。什麼df2['Check']正在做的是,如果df['date'] == 'October'然後我給你0,否則爲1基於另一個數據幀值創建列

np.where正常工作與其他條件,但strftime不順心的一系列導致此錯誤:

Traceback (most recent call last): 
    File "C:/Users/Leb/Desktop/Python/test2.py", line 22, in <module> 
    df2['Check'] = np.where(datetime.datetime.strftime(df['date'],'%B')=='October',0,1) 
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'Series' 

如果我循環需要很長一段時間我的實際數據約爲1M。我怎樣纔能有效地做到這一點?

df2['Check']應該是這樣的:

Check 
0  0 
1  0 
2  0 
3  0 
4  1 
5  1 
6  1 
7  1 
+0

使用'.dt'訪問器。使用熊貓0.17。請參閱[文檔](http://pandas.pydata.org/pandas-docs/version/0.17.0/whatsnew.html#dt-accessor)。你得到的錯誤,因爲日期時間與單個參數,而不是數組。 – Kartik

+0

非常有用,我會記住這一點。部分蟒蛇我現在有0.16。 – Leb

+0

不應該'df ['date']。dt.month == 9'即使在'0.16.0'也能正常工作嗎? – EdChum

回答

3

這是一個稍微簡單的版本,使用datetime對象的month屬性。如果等於10,就真/假值映射到你想要的0/1對:

df2['Check']=df.date.apply(lambda x: x.month==10).map({True:0,False:1}) 
0

@ AKO的答案是在錢上,而是基於@卡爾蒂克的和@ EdChum的評論這裏是我想出了與:

import pandas as pd 
import io 
import numpy as np 

data = """ 
    2015-10-31 50230 
    2015-10-31 48646 
    2015-10-31 48748 
    2015-10-31 46992 
    2015-11-01 46491 
    2015-11-01 45347 
    2015-11-01 45681 
    2015-11-01 46430 
    """ 

df = pd.read_csv(io.StringIO(data*125000), delimiter='\s+', index_col=False, names=['date','id'], parse_dates = ['date']) 

df2 = pd.DataFrame(index=df.index) 

df.shape 
(1125000, 2) 

%timeit df2['Check']=df.date.apply(lambda x: x.month==10).map({True:0,False:1}) 
1 loops, best of 3: 2.56 s per loop 

%timeit df2['date'] = np.where(df['date'].dt.month==10,0,1) 
10 loops, best of 3: 80.5 ms per loop 
相關問題