2016-11-05 9 views
1

私はデータフレーム「df_ret_temp」を持っているなぜdataframe.appyコストあまりにも多くの時間

enter image description here

enter image description here 私は列accMonth値を設定します。私は、列accMonth values.Theコードを設定する機能を適用する際に使用 コードがありますが、あまりにも多くの時間を要し、しかし速い

df_ret_temp.loc[df_ret_temp['tradeDate'].str[5:7]<='03','accMonth']=df_ret_temp['tradeDate'].str[0:4].apply(lambda x:str(int(x)-1))+'12' 
df_ret_temp.loc[(df_ret_temp['tradeDate'].str[5:7]<='06') & 
       (df_ret_temp['tradeDate'].str[5:7]>'03'),'accMonth']=df_ret_temp['tradeDate'].str[0:4]+'03' 

df_ret_temp.loc[(df_ret_temp['tradeDate'].str[5:7]<='09') & 
       (df_ret_temp['tradeDate'].str[5:7]>'06'),'accMonth']=df_ret_temp['tradeDate'].str[0:4]+'06' 

df_ret_temp.loc[(df_ret_temp['tradeDate'].str[5:7]<='12') & 
       (df_ret_temp['tradeDate'].str[5:7]>'09'),'accMonth']=df_ret_temp['tradeDate'].str[0:4]+'09' 

を実行します。

def df_ret_tempFun(row): 
    if row['tradeDate'][5:7]<='03': 
     row['accMonth']=str(int(row['tradeDate'][0:4])-1)+'12' 
    elif row['tradeDate'][5:7]<='06' and row['tradeDate'][5:7]>'03': 
     row['accMonth']=row['tradeDate'][0:4]+'03' 
    elif row['tradeDate'][5:7]<='09' and row['tradeDate'][5:7]>'06': 
     row['accMonth']=row['tradeDate'][0:4]+'06' 
    else: 
     row['accMonth']=row['tradeDate'][0:4]+'09' 
    return row 
df_ret_temp=df_ret_temp.apply(df_ret_tempFun,axis=1) 

なぜ、適用機能のパフォーマンスが低下しますか?

答えて

2

.apply(..., axis=1)はフードの下にあるループなので、ベクトル化されていないので、非常にです。

しかし、あなたの質問はここでXY problem

の非常に良い例は、あなたの質問;-)「尋ねない」ためのパンダソリューションです:

In [33]: x 
Out[33]: 
     Date 
0 2007-01-01 
1 2007-04-02 
2 2007-08-03 
3 2007-11-04 

In [34]: x.dtypes 
Out[34]: 
Date object 
dtype: object 

最初のごDate列がであることを確認してくださいdatetime DTYPE:

In [35]: x.Date = pd.to_datetime(x.Date) 

In [36]: x.dtypes 
Out[36]: 
Date datetime64[ns] 
dtype: object 

ベクトル化ソリューション:

In [37]: x['accMonth'] = pd.PeriodIndex(pd.PeriodIndex(df.Date, freq='Q') - 1, freq='3M') 

In [38]: x 
Out[38]: 
     Date accMonth 
0 2007-01-01 2006-12 
1 2007-04-02 2007-03 
2 2007-08-03 2007-06 
3 2007-11-04 2007-09 
関連する問題