n10*_*000 2 python multi-index pandas
我有一个像这样的数据帧:
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
Run Code Online (Sandbox Code Playgroud)
我只想选择列中值大于 0 的行c。我想我将不得不使用pd.IndexSlice仅选择二级索引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
Run Code Online (Sandbox Code Playgroud)
所以,现在我希望我可以简单地做df[df.loc[:,idx[:,['c']]] > 0],但是这给了我一个意想不到的结果:
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
Run Code Online (Sandbox Code Playgroud)
我想要的是所有值(不是NaNs),并且只有任何 c 列大于 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
Run Code Online (Sandbox Code Playgroud)
所以,我可能需要潜入某个any()地方,但是,我不知道该怎么做。任何提示?