Python Pandas - 选择等于的数据框列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45967512/
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 04:21:29  来源:igfitidea点击:

Python Pandas - select dataframe columns where equals

pythonpandas

提问by Dread

What is the Pandas equivalent of this SQL code?

这个 SQL 代码的 Pandas 等价物是什么?

Select id, fname, lname from table where id = 123

I know that this is the equivalent of an SQL 'where' clause in Pandas:

我知道这相当于 Pandas 中的 SQL 'where' 子句:

df[df['id']==123]

And this selects specific columns:

这将选择特定的列:

df[['id','fname','lname']]

But I can't figure out how to combine them. All examples I've seen online select all columns with conditions. I want to select a limited number of columns with one or more conditions.

但我无法弄清楚如何将它们结合起来。我在网上看到的所有示例都选择了所有带有条件的列。我想选择具有一个或多个条件的有限数量的列。

回答by MaxU

Use SQL-like .query()method:

使用类似 SQL 的.query()方法:

df.query("id == 123")[['id','fname','lname']]

or

或者

df[['id','fname','lname']].query("id == 123")

or more "Pandaic":

或更多“Pandaic”:

df.loc[df['id'] == 123, ['id','fname','lname']]