切片pandas DataFrame,其中列的值存在于另一个数组中

rya*_*lon 6 python numpy pandas

我有pandas.DataFrame大量的数据.在一列中随机重复键.在另一个数组中,我有一个theys键的列表,我想从中切割出DataFrame来自其行中其他列的数据.

钥匙:

keys = numpy.array([1,5,7])
Run Code Online (Sandbox Code Playgroud)

数据:

 indx   a      b     c   d
    0   5   25.0  42.1  13
    1   2   31.7  13.2   1
    2   9   16.5   0.2   9
    3   7   43.1  11.0  10
    4   1   11.2  31.6  10
    5   5   15.6   2.8  11
    6   7   14.2  19.0   4
Run Code Online (Sandbox Code Playgroud)

DataFrame如果列a中的值与来自的值匹配,我想切片所有行keys.

期望的结果:

 indx   a      b     c   d
    0   5   25.0  42.1  13
    3   7   43.1  11.0  10
    4   1   11.2  31.6  10
    5   5   15.6   2.8  11
    6   7   14.2  19.0   4
Run Code Online (Sandbox Code Playgroud)

DSM*_*DSM 10

你可以使用isin:

>>> df[df.a.isin(keys)]
      a     b     c   d
indx                   
0     5  25.0  42.1  13
3     7  43.1  11.0  10
4     1  11.2  31.6  10
5     5  15.6   2.8  11
6     7  14.2  19.0   4

[5 rows x 4 columns]
Run Code Online (Sandbox Code Playgroud)

或者query:

>>> df.query("a in @keys")
      a     b     c   d
indx                   
0     5  25.0  42.1  13
3     7  43.1  11.0  10
4     1  11.2  31.6  10
5     5  15.6   2.8  11
6     7  14.2  19.0   4

[5 rows x 4 columns]
Run Code Online (Sandbox Code Playgroud)