Python 为什么dataframe.appy花费了太多时间
我有一个数据帧“df_ret_temp” 我想设置列accMonth值。 有些代码运行得很快Python 为什么dataframe.appy花费了太多时间,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据帧“df_ret_temp” 我想设置列accMonth值。 有些代码运行得很快 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.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'
df_ret_temp.loc[df_ret_temp['tradeDate'].str[5:7].apply(…,axis=1)
是引擎盖下x的循环,因此它不是矢量化的,因此速度非常慢
但你的问题是一个很好的例子
以下是您“不问”问题的解决方案:-)问题:
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
d类型:
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
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