如何在嵌套列集中过滤熊猫数据框?

时间:2018-06-20 09:16:12

标签: python pandas dataframe select

我有以下熊猫数据框:

+---+-------------+-------------+
|   | Col1        |             |
+   +-------------+-------------+
|   | Sub1 | Sub2 | SubX | SubY |
+---+------+------+------+------+
| 0 | N    | A    | 1    | Z    |
| 1 | N    | B    | 1    | Z    |
| 2 | N    | C    | 2    | Z    |
| 3 | N    | D    | 2    | Z    |
| 4 | N    | E    | 3    | Z    |
| 5 | N    | F    | 3    | Z    |
| 6 | N    | G    | 4    | Z    |
| 7 | N    | H    | 4    | Z    |
+---+------+------+------+------+

我想按列 SubX 过滤数据框,所选行的值应为 3 ,如下所示:

+---+-------------+-------------+
|   | Col1        |             |
+   +-------------+-------------+
|   | Sub1 | Sub2 | SubX | SubY |
+---+------+------+------+------+
| 4 | N    | E    | 3    | Z    |
| 5 | N    | F    | 3    | Z    |
+---+------+------+------+------+

您能帮您找到正确的熊猫查询吗?由于嵌套的列结构,这对我来说很难。非常感谢!

1 个答案:

答案 0 :(得分:1)

我扩展了多索引层次结构,因为我不清楚空白应该是什么。

df

import matplotlib.animation as animation
import matplotlib.pyplot as plt


class Example:
    def __init__(self):
        self.fig, self.ax = plt.subplots()

    def update(self, i):
        print("This is getting called {}".format(i))
        self.ax.plot([i,i+1],[i,i+2])

    def animate(self):
        self.ani = animation.FuncAnimation(self.fig, self.update, interval=100)


def main():
    obj = Example()
    obj.animate()
    plt.show()


if __name__ == "__main__":
    main()

现在执行以下操作:

    Col1            Col2
    Sub1    Sub2    SubX    SubY
0   N       A       1       Z
1   N       B       1       Z
2   N       C       2       Z
3   N       D       2       Z
4   N       E       3       Z
5   N       F       3       Z
6   N       G       4       Z
7   N       H       4       Z

输出

df[df['Col2','SubX']==3]