python - Pandas:根据另一列中的值按名称对多个列进行子集

标签 python pandas

我无法理解 Pandas 的语法。以下是一些示例数据:

one  two   three  id
12   34    561    13555
2    67    781    14777 
34   12    90     13555    
5    67    89     14777

我想返回第一列、第二列和 id,其中 id 列中的值为 13555。想要按名称而不是位置选择列。

输出如下所示:

one  two  id
12   34   13555
34   12   13555    

最佳答案

您可以尝试locisin :

print df.loc[(df.id.isin([13555])), ['one', 'two', 'id']]

   one  two     id
0   12   34  13555
2   34   12  13555

或者:

df = df[['one', 'two', 'id']]
print df
   one  two     id
0   12   34  13555
1    2   67  14777
2   34   12  13555
3    5   67  14777

print df[df.id == 13555]
   one  two     id
0   12   34  13555
2   34   12  13555

print df[['one', 'two', 'id']][df.id == 13555]
   one  two     id
0   12   34  13555
2   34   12  13555

或者使用query :

print df[['one', 'two', 'id']].query("id == 13555")
   one  two     id
0   12   34  13555
2   34   12  13555

关于python - Pandas:根据另一列中的值按名称对多个列进行子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34963812/

相关文章:

python - 为什么管道被用作 GridsearchCV 的一部分,而不是相反?

python - 如何使用 pandas 查找文本数据中单词的出现频率并将其写入 csv 文件

python - 如何让 Bokeh 的 'PointDrawTool' 与 NetworkX Spring_Layout 一起使用

python - Django 查询检索被选为外键的项目?

python-2.7 - 修改 Pandas 图中的背景颜色?

python - pandas.read_csv : how do I parse two columns as datetimes in a hierarchically-indexed CSV?

python - 如何在 unstack 过程中使用自定义列名称并更改结构?

Python Pandas : creating condensed dataframe

python - 在 Pandas 数据帧上使用 .replace() 方法时字典中的重叠键

python - 如何在 Snakemake 中使用 plink 定义两个规则