gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:56:15 24 4
gpt4 key购买 nike

我无法理解 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com