不能遗忘的 np.where

要解决的问题:

把下图左边的文件中第二列等于1的行全部提取出来单独保存成 txt 文件(如下图的右边图所示)

思路

目标 txt 文件中没有标点符号,可以直接用 np.loadtxt 函数读入成数组,因为数组才有行和列的关系,方面操作,而且也有专门的数组保存成 txt 文件的函数 np.save.txt ,然后就是想方法找出符合要求的行号,有行号就可以通过数组索引来找到这些行,np.where 函数刚好实现的就是该功能,那么问题迎刃而解,嘻嘻嘻

np.where(a[:,1]==1)[0] 返回a数组第二列中等于1的 行 的索引
np.where(a[:,1]==1)[1] 返回a数组第二列中等于1的 列 的索引

不能遗忘的 np.where_第1张图片

完整代码:

文件位置(都在桌面)

不能遗忘的 np.where_第2张图片

保存的 txt 文件

不能遗忘的 np.where_第3张图片

div.py 文件

import numpy as np

file="C:/Users/Chengguo/Desktop/4after_9101-9850-2.txt"

a = np.loadtxt(file)
print(a,len(a),a.shape)


#参考文章:https://blog.csdn.net/scutjy2015/article/details/73942354
b = np.where(a[:,1]==1)[0]#返回行号
print(b,len(b))

print(a[b,:])#按行号索引,找到所有的行组成新的数组


for i in range(6):
    num = i+1
    b = np.where(a[:,1]==num)[0]
    np.savetxt("C:/Users/Chengguo/Desktop/div/%08d.txt"%num,a[b,:],fmt="%d %d %.1f %.1f", delimiter="\n")

参考文章

1 MATLAB 的 find 和 python 的 np.where

你可能感兴趣的:(机器学习,python,txt,numpy)