2017-07-21 90 views
0

一定有什么是熊猫数据帧办法的办法比迭代循环等这个问题...大熊猫价格统计

给定一组列表价格可随时间变化零星(多达在70倍季度,但仅限于某个日期,没有时间),包括价格上涨和下跌,我正在寻找起始价格,最终价格,最高价格,最低价格,平均价格以及本季度45天内的价格。

list_prices = [ 
    {'product': 'prodA', 'price': 68.40, 'eff_date': '2016-12-01'}, 
    {'product': 'prodA', 'price': 69.50, 'eff_date': '2017-02-17'}, 
    {'product': 'prodB', 'price': 34.20, 'eff_date': '2015-10-18'}, 
    {'product': 'prodB', 'price': 32.55, 'eff_date': '2016-01-07'}, 
    {'product': 'prodC', 'price': 19.95, 'eff_date': '2017-03-01'}, 
    ] 

和计算为2017Q1,

quarter product start end min max  mean day45 
0 prodA 2017Q1 68.4 69.5 68.4 69.5 68.92556 68.4 
1 prodB 2017Q1 32.2 32.55 34.2 32.55  32.66 32.55 
2 prodC 2017Q1 NaN 19.95 19.95 19.95  19.95 NaN 

结果被计算为在一个时间4分之4,所以结果是PROD的矩阵,QTR为行索引,开始,结束,最小值,最大值,意思是中间

OHLC重采样可以工作,但是当日期超出季度日期时还没有找到正确的技术。

所以...有没有一种可行的方法来解决这个问题?

回答

0
df = pd.DataFrame(list_prices) 

# convert eff_date to datetime object 
df['eff_date'] = pd.to_datetime(df['eff_date']) 

# set eff_date as index. helps with grouping by quarter 
df.set_index('eff_date', inplace=True) 

def get_metrics(x): 

    # start of the quarter 
    start = x.iloc[0] 

    # end of the quarter 
    end = x.iloc[-1] 

    # middle of the quarter 
    mid_date_index = int(len(x)/2) 
    mid = x.iloc[mid_date_index] 

    max = x.max() 
    min = x.min() 
    mean = x.mean() 

    return pd.Series({'max': max, 'min': min, 'mean': mean, 'start': start, 'end': end, 'mid': mid}) 

# groupby product and quarter and get all the metrics 
df.groupby(['product', pd.TimeGrouper('Q')])['price'].apply(get_metrics).unstack()