I have a DataFrame like this:
df = pd.DataFrame(np.random.randn(6, 6),
columns=pd.MultiIndex.from_arrays((['A','A','A','B','B','B'],
['a', 'b', 'c', 'a', 'b', 'c'])))
df
A B
a b c a b c
0 -0.089902 -2.235642 0.282761 0.725579 1.266029 -0.354892
1 -1.753303 1.092057 0.484323 1.789094 -0.316307 0.416002
2 -0.409028 -0.920366 -0.396802 -0.569926 -0.538649 -0.844967
3 1.789569 -0.935632 0.004476 -1.873532 -1.136138 -0.867943
4 0.244112 0.298361 -1.607257 -0.181820 0.577446 0.556841
5 0.903908 -1.379358 0.361620 1.290646 -0.523404 -0.518992
I would like to select only the rows that have a value larger than 0 in column c. I figured that I will have to use pd.IndexSlice to select only the second level index c.
idx = pd.IndexSlice
df.loc[:,idx[:,['c']]] > 0
A B
c c
0 True False
1 True True
2 False False
3 True False
4 False True
5 True False
So, now I would expect that I could simply do df[df.loc[:,idx[:,['c']]] > 0], however that gives me an unexpected result:
df[df.loc[:,idx[:,['c']]] > 0]
A B
a b c a b c
0 NaN NaN 0.282761 NaN NaN NaN
1 NaN NaN 0.484323 NaN NaN 0.416002
2 NaN NaN NaN NaN NaN NaN
3 NaN NaN 0.004476 NaN NaN NaN
4 NaN NaN NaN NaN NaN 0.556841
5 NaN NaN 0.361620 NaN NaN NaN
What I would have liked to have is all values (not NaNs) and only the rows where any of the c-columns is greater 0.
A B
a b c a b c
0 -0.089902 -2.235642 0.282761 0.725579 1.266029 -0.354892
1 -1.753303 1.092057 0.484323 1.789094 -0.316307 0.416002
3 1.789569 -0.935632 0.004476 -1.873532 -1.136138 -0.867943
4 0.244112 0.298361 -1.607257 -0.181820 0.577446 0.556841
5 0.903908 -1.379358 0.361620 1.290646 -0.523404 -0.518992
So, I would probably need to sneak an any() somewhere in there, however, I am not sure how to do that. Any hints?