具有不同偏移量向量的Pandas矢量化日期偏移量操作

2024-04-25 15:18:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试执行以下操作,但似乎不支持此模式下的矢量化操作。在

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

这是为代码段中的最后一条语句返回的警告:

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: Adding/subtracting array of DateOffsets to Series not vectorized "Series not vectorized", PerformanceWarning)

我想这是一个矢量化的操作,因为性能的好处。在

谢谢。在

编辑

最后,比较@john zwinck的以下方法:

^{pr2}$

结果是:

index year  month  day  month_offset     mydate    offset1      final
0  2017      1    1             1 2017-01-01 2017-01-31 2017-01-31
1  2017      1    1             2 2017-01-01 2017-02-28 2017-02-28
2  2017      1    1             3 2017-01-01 2017-03-31 2017-03-31
3  2017      1    1             4 2017-01-01 2017-04-30 2017-04-30
4  2017      1    1             5 2017-01-01 2017-05-31 2017-05-31
5  2017      1    1             6 2017-01-01 2017-06-30 2017-06-30
6  2017      1    1             7 2017-01-01 2017-07-31 2017-07-31


runfile('C:/bitbucket/test/vector_dates.py', wdir='C:/bitbucket/test')
Method 1 0.003999948501586914 seconds
Method 2 with numpy vectorization 0.0009999275207519531 seconds

很明显,numpy要快得多


Tags: lambdapypandasdfdateyear矢量化offset
2条回答

一种真正的矢量化方法是从month_offset构造一个numpy.timedelta64数组,将其添加到日期数组中,然后减去numpy.timedelta64(1, 'D')返回上个月的最后一天。在

使用apply(lambda)的解决方案可能要慢得多。正如警告所说,有些大熊猫的日期偏移操作没有矢量化。如果你的数据很大,最好避免它们。NumPy工具,如busday_offset()和{}完全可以执行。在

考虑以下方法:

In [94]: df['date'] = pd.to_datetime(df[['year','month','day']])

In [95]: df['date_offset'] = df.apply(lambda x: x['date'] + pd.offsets.MonthEnd(x['month_offset']), axis=1)

In [96]: df
Out[96]:
   year  month  day  month_offset       date date_offset
0  2017      1   15             1 2017-01-15  2017-01-31
1  2017      1   15             2 2017-01-15  2017-02-28
2  2017      1   15             3 2017-01-15  2017-03-31
3  2017      1   15             4 2017-01-15  2017-04-30
4  2017      1   15             5 2017-01-15  2017-05-31
5  2017      1   15             6 2017-01-15  2017-06-30
6  2017      1   15             7 2017-01-15  2017-07-31

相关问题 更多 >