python - 如何在Python中的数据集的两个不同列中找到相同值的匹配

标签 python sorting numpy

我有一个 .txt 文件格式的数据集,如下所示:

# ID M R x y z
  0 1 200 2 2 2 
  1 5 300 2 4 6 
  2 5 600 2 4 2
  3 4 500 2 2 5
  4 4 500 3 2 1
  5 7 300 2 4 1

我想打印 x 列和 y 列中具有相同值的行的 ID

我写了一篇文章,但它没有达到我想要的效果:

import numpy as np
halo = 'test.txt'
ID, m,r,x,y,z= np.loadtxt(halo)


for yv in np.unique(halo[3] and halo[4]):
    if yv != np.nan:
        idx = x == yv

print idx

基本上我想要如下的输出:

[0, 3]
[1, 2, 5]

其中包含 x 和 y 中具有相同值的 ID 列值。非常感谢您的帮助。

最佳答案

这可以用 pandas 来完成,

import pandas as pd
df = pd.read_csv('path_to_your_txt_file')
rows = df[df['x'] == df['y']]

其中 rows.index = [0, 3]

关于python - 如何在Python中的数据集的两个不同列中找到相同值的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51600468/

相关文章:

python - numpy 数组元素是否自动舍入?

python - 查找并打印子元素具有相似值的所有行

python - 如果行包含 DD/MM/YY 打印行中的日期

python - 使用 exec 进行变量赋值是Pythonic吗?

r - 在本地环境中创建 S3 类以对对象进行排序

python按排序顺序递归合并2个列表

sorting - Elasticsearch按嵌套对象排序

python - 使用 Pipenv 开发 Python 库

python - Bottle 路由处理 POST 和 GET

python - 从拟合分布中抽取