简体   繁体   English

在 Pandas 数据框中查找元素

[英]Finding elements in a pandas dataframe

I have a pandas dataframe which looks like the following:我有一个如下所示的 Pandas 数据框:

0 1
0 2
2 3
1 4

What I want to do is the following: if I get 2 as input my code is supposed to search for 2 in the dataframe and when it finds it returns the value of the other column.我想要做的是:如果我得到 2 作为输入,我的代码应该在数据框中搜索 2,当它找到时返回另一列的值。 In the above example my code would return 0 and 3. I know that I can simply look at each row and check if any of the elements is equal to 2 but I was wondering if there is one-liner for such a problem.在上面的示例中,我的代码将返回 0 和 3。我知道我可以简单地查看每一行并检查是否有任何元素等于 2,但我想知道是否有针对此类问题的单行代码。

UPDATE: None of the columns are index columns.更新:所有列都不是索引列。

Thanks谢谢

>>> df = pd.DataFrame({'A': [0, 0, 2, 1], 'B': [1,2,3,4]})
>>> df
   A  B
0  0  1
1  0  2
2  2  3
3  1  4

The following pandas syntax is equivalent to the SQL SELECT B FROM df WHERE A = 2以下 Pandas 语法等效于 SQL SELECT B FROM df WHERE A = 2

>>> df[df['A'] == 2]['B']
2    3
Name: B, dtype: int64

There's also pandas.DataFrame.query :还有pandas.DataFrame.query

>>> df.query('A == 2')['B']
2    3
Name: B, dtype: int64

You may need this:你可能需要这个:

n_input = 2

df[(df == n_input).any(1)].stack()[lambda x: x != n_input].unique()
# array([0, 3])

 df = pd.DataFrame({'A': [0, 0, 2, 1], 'B': [1,2,3,4]}) t = [df.loc[lambda df: df['A'] == 3]] t

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM