python - Logical MultiIndexing in Pandas -
is there way extract values of b
index one
c
greater zero? want extract values -0.22
, -1.21
.
import numpy np import pandas pd arrays =[np.array(['one','one','one','two','two','two']),np.array(['a','b','c','a','b','c'])] df = pd.dataframe(np.random.randn(6,5),index=arrays) df 0 1 2 3 4 1 -0.908680 0.031505 -0.087090 -0.039527 0.221196 b 1.010757 1.272553 -0.220535 -1.216996 -0.122108 c -0.781714 -1.830215 0.584311 0.010987 -0.050355 2 -0.331269 0.410596 0.569802 1.455710 0.377796 b 0.079330 -2.538031 -1.665904 0.477257 0.500805 c -0.388749 2.188289 -1.465292 0.594870 -0.031983
you can create mask
, use loc
mask
:
import numpy np import pandas pd np.random.seed(1) arrays = [np.array(['one','one','one','two','two','two']), np.array(['a','b','c','a','b','c'])] df = pd.dataframe(np.random.randn(6,5),index=arrays) print (df) 0 1 2 3 4 1 1.624345 -0.611756 -0.528172 -1.072969 0.865408 b -2.301539 1.744812 -0.761207 0.319039 -0.249370 c 1.462108 -2.060141 -0.322417 -0.384054 1.133769 2 -1.099891 -0.172428 -0.877858 0.042214 0.582815 b -1.100619 1.144724 0.901591 0.502494 0.900856 c -0.683728 -0.122890 -0.935769 -0.267888 0.530355 idx = pd.indexslice mask = (df.loc[idx['one', 'c'],:]) > 0 print (mask) 0 true 1 false 2 false 3 false 4 true name: (one, c), dtype: bool print (df.loc[idx['one', 'b'], mask]) 0 -2.301539 4 -0.249370 name: (one, b), dtype: float64
Comments
Post a Comment