我正在尝试执行以下操作,但似乎不支持此模式下的矢量化操作。
import pandas as pd
df=pd.DataFrame([[2017,1,15,1],
[2017,1,15,2],
[2017,1,15,3],
[2017,1,15,4],
[2017,1,15,5],
[2017,1,15,6],
[2017,1,15,7]],
columns=['year','month','day','month_offset'])
df['date']=df.apply(lambda g: pd.datetime(g.year,g.month,g.day),axis=1)
df['offset']=df.apply(lambda g: pd.offsets.MonthEnd(g.month_offset),axis=1)
df['date_offset']=df.date+df.offset
Run Code Online (Sandbox Code Playgroud)
这是代码片段中最后一条语句返回的警告:
C:\Python3.5.2.3\WinPython-64bit-3.5.2.3\python-3.5.2.amd64\lib\site-packages\pandas\core\ops.py:533: PerformanceWarning: 添加/减去 DateOffsets 数组到系列未矢量化“系列未矢量化”,性能警告)
由于性能优势,我希望将其用作矢量化操作。
谢谢。
最后,比较@john-zwinck 的方法:
import time
import pandas as pd
import numpy as np
df=pd.DataFrame([[2017,1,1,1],
[2017,1,1,2],
[2017,1,1,3],
[2017,1,1,4],
[2017,1,1,5],
[2017,1,1,6],
[2017,1,1,7]],
columns=['year','month','day','month_offset'])
df['mydate']=df.apply(lambda g:
pd.datetime(g.year,g.month,g.day),axis=1)
start_time=time.time()
df['pandas_offset']=df.apply(lambda g: g.mydate +
pd.offsets.MonthEnd(g.month_offset),axis=1)
end_time=time.time()
print('Method1 {} seconds'.format(end_time-start_time))
start_time=time.time()
df['numpy_offset']=(df.mydate.values.astype('M8[M]')+
df.month_offset.values * np.timedelta64(1, 'M')).astype('M8[D]') -
np.timedelta64(1, 'D')
end_time=time.time()
print('Method3 with numpy vectorization {} seconds'.format(end_time-
start_time))
Run Code Online (Sandbox Code Playgroud)
结果: …