简体   繁体   English

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

[英]Slice pandas DataFrame where column's value exists in another array

I have a pandas.DataFrame with a large amount of data. 我有一个包含大量数据的pandas.DataFrame In one column are randomly repeating keys. 在一列中随机重复键。 In another array I have a list of of theys keys for which I would like to slice from the DataFrame along with the data from the other columns in their row. 在另一个数组中,我有一个我想要从DataFrame切片的theys键列表以及它们行中其他列的数据。

keys : 钥匙

keys = numpy.array([1,5,7])

data : 数据

 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

I would like slice all rows from the DataFrame if the value in the column a matches a value from keys . 如果列a中的值与keys中的值匹配,我想从DataFrame切片所有行。

Desired result : 期望的结果

 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

You can use isin : 你可以使用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]

or query : 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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python pandas dataframe:删除列中的值存在于另一个中的行 - Python pandas dataframe: delete rows where value in column exists in another 如何将一列除以另一列,其中一个数据帧的列值对应于 Python Pandas 中另一个数据帧的列值? - How to divide one column by another where one dataframe's column value corresponds to another dataframe's column's value in Python Pandas? 熊猫:排序数据框是列值存在于另一个数据框中 - Pandas: Sort Dataframe is Column Value Exists in another Dataframe 对于Pandas数据框中的每一行,确定另一列中是否存在一列值 - For every row in Pandas dataframe determine if a column value exists in another column 通过索引和列名称数组切片Pandas数据帧 - Slice a Pandas dataframe by an array of indices and column names 按列中的部分字符串值对熊猫数据框进行切片 - Slice pandas dataframe by part of string value in column 删除 Pandas 数据框中所有元素的最佳方法是什么,其中一列中的值在另一列中多次存在? - What is the best way to remove all elements in a pandas dataframe where a value in one columns exists more than once in another column? Python Pandas - 根据要匹配到列名的另一个表的值切片 DataFrame - Python Pandas - Slice DataFrame based on Another Table's Values to Match to Column Name 如何检查值是否存在于另一个熊猫数据框中? - How to check if value exists in another dataframe in pandas? 计算pandas dataframe中列表中的列是否存在值 - Compute if value exists in a column on lists in pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM