2016-11-14 144 views
2

跟蹤所有模擬結果的一個參數來看,我創建大熊貓命名dfParRun一個MultIndex數據框如下:切片大熊貓多指標數據幀

import pandas as pd 
import numpy as np 
import itertools 
limOpt = [0.1,1,10] 
reimbOpt = ['Cash','Time'] 
xOpt = [0.1, .02, .03, .04, .05, .06, .07, .08] 
zOpt = [1,5n10] 
arrays = [limOpt, reimbOpt, xOpt, zOpt] 
parameters = list(itertools.product(*arrays)) 
nPar = len(parameters) 

variables = ['X', 'Y', 'Z'] 
nVar = len(variables) 
index = pd.MultiIndex.from_tuples(parameters, names=['lim', 'reimb', 'xMax', 'zMax']) 

dfParRun = pd.DataFrame(np.random.rand((nPar, nVar)), index=index, columns=variables) 

分析我的參數來看,我想切片這個數據幀,但這似乎是一個負擔。例如,我想有大於0.5,LIM等於10.在這一刻XMAX所有的結果,唯一的工作方法,我發現是:

df = dfParRun.reset_index() 
df.loc[(df.xMax>0.5) & (df.lim==10)] 

,我不知道是否有一種方法,無需重新設置指數DataFrame的?

回答

2

選項1
使用pd.IndexSlice
注意:需要sort_index

dfParRun.sort_index().loc[pd.IndexSlice[10, :, .0500001:, :]] 

enter image description here

選項2
ù SE您df有後reset_index

df.query('xMax > 0.05 & lim == 10') 

enter image description here


設置

import pandas as pd 
import numpy as np 
import itertools 
limOpt = [0.1,1,10] 
reimbOpt = ['Cash','Time'] 
xOpt = [0.1, .02, .03, .04, .05, .06, .07, .08] 
zOpt = [1, 5, 10] 
arrays = [limOpt, reimbOpt, xOpt, zOpt] 
parameters = list(itertools.product(*arrays)) 
nPar = len(parameters) 

variables = ['X', 'Y', 'Z'] 
nVar = len(variables) 
index = pd.MultiIndex.from_tuples(parameters, names=['lim', 'reimb', 'xMax', 'zMax']) 

dfParRun = pd.DataFrame(np.random.rand(*(nPar, nVar)), index=index, columns=variables) 
df = dfParRun.reset_index() 
+0

THX!似乎對索引進行排序是我對如何使用DataFrame的理解所缺少的。沒有排序,該功能出錯。 –