熊猫:比前滚更快的方法?

时间:2016-03-14 15:57:26

标签: python pandas

我正在为队列分析准备一些数据。我所拥有的信息类似于可以使用以下代码生成的虚假数据集:

import random
import numpy as np
import pandas as pd
from pandas import Series, DataFrame

# prepare some fake data to build frames
subscription_prices = [x - 0.05 for x in range(100, 500, 25)]
companies = ['initech','ingen','weyland','tyrell']
starting_periods = ['2014-12-10','2015-1-15','2014-11-20','2015-2-9']

# use the lists and dict from above to create a fake dataset
pieces = []
for company, period in zip(companies,starting_periods):
    data = {
        'company': company,
        'revenue': random.choice(subscription_prices),
        'invoice_date': pd.date_range(period,periods=12,freq='31D')
    }
    frame = DataFrame(data)
    pieces.append(frame)
df = pd.concat(pieces, ignore_index=True)

我需要将发票日期标准化为月度。出于多种原因,最好将所有invoice_date值移至月末。我用这个方法:

from pandas.tseries.offsets import *
df['rev_period'] = df['invoice_date'].apply(lambda x: MonthEnd(normalize=True).rollforward(x))

然而,即使只有一百万行(这是我实际数据集的大小),这也变得非常缓慢:

In [11]: %time df['invoice_date'].apply(lambda x: MonthEnd(normalize=True).rollforward(x))
CPU times: user 3min 11s, sys: 1.44 s, total: 3min 12s
Wall time: 3min 17s

关于这种带有Pandas的日期抵消方法的重要部分是,如果invoice_date恰好落在该月的最后一天,那么该日期将保持为该月的最后一天。另一个好处是,这使dtype保持为datetime,而df['invoice_date'].apply(lambda x: x.strftime('%Y-%m'))更快,但将值转换为str

有没有矢量化的方法呢?我尝试了MonthEnd(normalize=True).rollforward(df['invoice_date']),但收到了错误TypeError: Cannot convert input to Timestamp

1 个答案:

答案 0 :(得分:2)

是的,有:

df['rev_period'] = df['invoice_date'] + pd.offsets.MonthEnd(0)

应该至少快一个数量级。