我无法理解 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
最佳答案
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/