python - 如何使用 numpy where 查找多条记录

标签 python numpy

我正在使用 numpy 读取 csv 文件。我正在尝试添加条件以匹配 csv 文件中的记录。 我的示例 team_file 如下所示

43596,Team1,50,team1data,id1 
43597,Team2,51,team2data,id2
43598,Team3,50,team2data,id2

下面是代码

import numpy as np
reader = np.genfromtxt(team_file, delimiter=',', usecols=np.arange(1, 3), dtype=None)

我想在column3为50时获取column2。 在此示例中,Team1 和 Team3 应该是输出。

我想使用 np.where 而不编写 for 循环。有没有办法使用 numpy 来实现这一点?我不能使用 Pandas 。 通过执行 reader[0][1] 给我的值为 50,但是我如何为文件中的所有记录实现它?
感谢任何帮助

最佳答案

In [90]: txt=b"""43596,Team1,50,team1data,id1 
    ...: 43597,Team2,51,team2data,id2
    ...: 43598,Team3,50,team2data,id2
    ...: """
In [92]: data=np.genfromtxt(txt.splitlines(),delimiter=',',usecols=[1,3],dtype=None)
In [93]: data
Out[93]: 
array([[b'Team1', b'team1data'],
       [b'Team2', b'team2data'],
       [b'Team3', b'team2data']],
      dtype='|S9')

无法测试“50”;任何“usecols”都没有这样的值。

<小时/>

如果我加载所有列,我可以测试第三个字段是否为“50”,选择适当的记录:

In [94]: data=np.genfromtxt(txt.splitlines(),delimiter=',',dtype=None)
In [95]: data
Out[95]: 
array([(43596, b'Team1', 50, b'team1data', b'id1'),
       (43597, b'Team2', 51, b'team2data', b'id2'),
       (43598, b'Team3', 50, b'team2data', b'id2')],
      dtype=[('f0', '<i4'), ('f1', 'S5'), ('f2', '<i4'), ('f3', 'S9'), ('f4', 'S3')])
In [96]: data['f2']
Out[96]: array([50, 51, 50])
In [97]: idx = np.where(data['f2']==50)
In [98]: idx
Out[98]: (array([0, 2], dtype=int32),)
In [99]: data[idx]
Out[99]: 
array([(43596, b'Team1', 50, b'team1data', b'id1'),
       (43598, b'Team3', 50, b'team2data', b'id2')],
      dtype=[('f0', '<i4'), ('f1', 'S5'), ('f2', '<i4'), ('f3', 'S9'), ('f4', 'S3')])
In [100]: data['f1'][idx]
Out[100]: 
array([b'Team1', b'Team3'],
      dtype='|S5')
<小时/>

更正。使用 arange(1,3) 而不是 [1,3] 来选择列

In [102]: data=np.genfromtxt(txt.splitlines(),delimiter=',',usecols=np.arange(1,
     ...: 3),dtype=None)
In [103]: data
Out[103]: 
array([(b'Team1', 50), (b'Team2', 51), (b'Team3', 50)],
      dtype=[('f0', 'S5'), ('f1', '<i4')])
In [104]: idx = np.where(data['f1']==50)
In [105]: data[idx]
Out[105]: 
array([(b'Team1', 50), (b'Team3', 50)],
      dtype=[('f0', 'S5'), ('f1', '<i4')])

关于python - 如何使用 numpy where 查找多条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45292386/

相关文章:

python - 使用 pandas.cut() 并将其设置为数据帧的索引

python - 将像素值显示为图像

python - Python字典中最大值的贪心算法

python - 使用 Django 1.8 部署时出现应用程序错误

python - 如何创建 4 或 8 连接的邻接矩阵

python - Keras fit_generator 引发 ValueError 因为多个输入不正确

python - 如何从 scipy LinearOperator 获取 numpy 数组?

Python递归错误

jquery - Django - Ajax HttpResponse 延迟

python - Alembic 不在自动生成中添加 Cascade 信息?