2017-10-10 133 views
1

我已經通過從數據傳遞者獲取面板並將其轉換爲多索引數據幀來創建庫存數據的多索引。有時當我使用.loc時,我會得到一個有1個索引的系列,有時我會得到一個有兩個索引的系列。我怎樣才能按日期分片,並獲得一個索引的系列?代碼將有助於...熊貓:切分多索引數據幀...簡單系列想要

import pandas_datareader.data as web 

# Define the securities to download 
symbols = ['AAPL', 'MSFT'] 

# Define which online source one should use 
data_source = 'yahoo' 

# Define the period of interest 
start_date = '2010-01-01' 
end_date = '2010-12-31' 

# User pandas_reader.data.DataReader to load the desired data. 
panel = web.DataReader(symbols, data_source, start_date, end_date) 

# Convert panel to multiindex dataframe 
midf = panel.to_frame() 

# for slicing multiindex dataframes it must be sorted 
midf = midf.sort_index(level=0) 

在這裏,我選擇列我想:

adj_close = midf['Adj Close'] 
adj_close.head() 

我得到兩個指數(Dateminor)系列:

Date  minor 
2010-01-04 AAPL  27.505054 
      SPY  96.833946 
2010-01-05 AAPL  27.552608 
      SPY  97.090271 
2010-01-06 AAPL  27.114347 
Name: Adj Close, dtype: float64 

現在我使用:選擇蘋果來選擇所有日期。

aapl_adj_close = adj_close.loc[:, 'AAPL'] 
aapl_adj_close.head() 

並得到一系列索引Date。這是我正在尋找的!

Date 
2010-01-04 27.505054 
2010-01-05 27.552608 
2010-01-06 27.114347 
2010-01-07 27.064222 
2010-01-08 27.244156 
Name: Adj Close, dtype: float64 

但是當我真正按日期片,我沒有得到系列:

sliced_aapl_adj_close = adj_close.loc['2010-01-04':'2010-01-06', 'AAPL'] 
sliced_aapl_adj_close.head() 

我得到兩個指數系列:

Date  minor 
2010-01-04 AAPL  27.505054 
2010-01-05 AAPL  27.552608 
2010-01-06 AAPL  27.114347 
Name: Adj Close, dtype: float64 

切片是正確的,值是正確的,但我不希望那裏的小指數(因爲我想通過這個系列來繪圖)。什麼是正確的方式來切片?

謝謝!

回答

4

您可以使用:

df = df.reset_index(level=1, drop=True) 

或者:

df.index = df.index.droplevel(1) 

另一種解決方案是通過unstack重塑爲DataFrame然後[]選擇:

df = adj_close.unstack() 

print (df) 
minor   AAPL  SPY 
Date        
2010-01-04 27.505054 96.833946 
2010-01-05 27.552608 97.090271 
2010-01-06 27.114347  NaN 

print (df['AAPL']) 

Date 
2010-01-04 27.505054 
2010-01-05 27.552608 
2010-01-06 27.114347 
Name: AAPL, dtype: float64 
+1

謝謝!這樣可行!但爲什麼這兩個切片會有不同的結果呢? 'adj_close.loc ['2010-01-04':'2010-01-06','AAPL']' 和 'adj_close.loc [:,'AAPL']' 看起來很相似。 –

+0

難題。也許是因爲第二種解決方案更一般,所以可以使用'adj_close.loc ['2010-01-04':'2010-01-05',['AAPL','SPY']]' – jezrael