pandas 在熊猫数据框中查找元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42796085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:11:40  来源:igfitidea点击:

Finding elements in a pandas dataframe

pythonpandasdataframe

提问by ahajib

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. 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.

我想要做的是:如果我得到 2 作为输入,我的代码应该在数据框中搜索 2,当它找到时返回另一列的值。在上面的示例中,我的代码将返回 0 和 3。我知道我可以简单地查看每一行并检查是否有任何元素等于 2,但我想知道是否有针对此类问题的单行代码。

UPDATE: None of the columns are index columns.

更新:所有列都不是索引列。

Thanks

谢谢

采纳答案by Psidom

You may need this:

你可能需要这个:

n_input = 2

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

回答by blacksite

>>> 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