2017-08-24 142 views
1

重新索引所以我有timeseries`的陣列是基於一個fund_id生成:ValueError異常:不能重複軸熊貓

def get_adj_nav(self, fund_id): 
    df_nav = read_frame(
     super(__class__, self).filter(fund__id=fund_id, nav__gt=0).exclude(fund__account_class=0).order_by(
      'valuation_period_end_date'), coerce_float=True, 
     fieldnames=['income_payable', 'valuation_period_end_date', 'nav', 'outstanding_shares_par'], 
     index_col='valuation_period_end_date') 
    df_dvd, skip = self.get_dvd(fund_id=fund_id) 
    df_nav_adj = calculate_adjusted_prices(
     df_nav.join(df_dvd).fillna(0).rename_axis({'payout_per_share': 'dividend'}, axis=1), column='nav') 
return df_nav_adj 

def json_total_return_table(request, fund_account_id): 
ts_list = [] 
for fund_id in Fund.objects.get_fund_series(fund_account_id=fund_account_id): 
    if NAV.objects.filter(fund__id=fund_id, income_payable__lt=0).exists(): 
     ts = NAV.objects.get_adj_nav(fund_id)['adj_nav'] 
     ts.name = Fund.objects.get(id=fund_id).account_class_description 
     ts_list.append(ts.copy()) 
     print(ts) 
    df_adj_nav = pd.concat(ts_list, axis=1) # ====> Throws error 
    cols_to_datetime(df_adj_nav, 'index') 
    df_adj_nav = ffn.core.calc_stats(df_adj_nav.dropna()).to_csv(sep=',') 

這樣的時間序列看怎麼樣一個例子是這樣的:

valuation_period_end_date 
2013-09-03 17.234000 
2013-09-04 17.277000 
2013-09-05 17.363000 
2013-09-06 17.326900 
2013-09-09 17.400800 
2013-09-10 17.473000 
2013-09-11 17.486800 
2013-09-12 17.371600 
.... 
Name: CLASS I, Length: 984, dtype: float64 

另一個時間序列:

valuation_period_end_date 
2013-09-03 17.564700 
2013-09-04 17.608500 
2013-09-05 17.696100 
2013-09-06 17.659300 
2013-09-09 17.734700 
2013-09-10 17.808300 
2013-09-11 17.823100 
2013-09-12 17.704900 
.... 
Name: CLASS F, Length: 984, dtype: float64 

對於每一個時間序列的長度是不同的,我想知道如果這是我得到的錯誤的原因:cannot reindex from a duplicate axis。我是熊貓新手,所以我想知道你們是否有任何建議。

謝謝

編輯:也索引不應該是唯一的。

回答

1

也許這樣的事情會起作用。我已將fund_id添加到數據框,並將其重新編入valuation_period_end_datefund_id

# Only fourth line above error. 
ts = (
    NAV.objects.get_adj_nav(fund_id['adj_nav'] 
    .to_frame() 
    .assign(fund_id=fund) 
    .reset_index() 
    .set_index(['valuation_period_end_date', 'fund_id'])) 

然後用axis=0,組上的日期和fund_id堆棧(假設每日期和fund_id只有一個唯一的值,可以取第一值),則取消堆疊fund_id樞轉它作爲列:

df_adj_nav = (
    pd.concat(ts_list, axis=0) 
    .groupby(['valuation_period_end_date', 'fund_id']) 
    .first() 
    .to_frame() 
    .unstack('fund_id')) 
+0

獲取錯誤:'系列'對象沒有屬性'賦值' – anderish

+0

請參閱上面的編輯。使用'to_frame()'將數據從系列轉換爲數據。 – Alexander

+0

例外:無法處理非唯一的多索引! – anderish