我正在尝试进行文件操作和重新分配,其中文件有 4 列,例如:
该文件有 2514 行和 4 列,格式为:
1 -0.000000 0.000000 0
2 -0.000000 0.000000 0
3 -7.009116 58.185083 1
4 -7.009116 58.185670 1
5 -7.009799 58.185410 0
6 -7.009996 58.184643 1
7 -7.009997 58.186257 1
8 -7.012637 58.182443 1
9 -7.013223 58.182150 1
10 -7.010877 58.184203 1
我的目标是将文件加载到 Python 中,并根据我将设置为标准的 x,y 设置值,他们会将标志值更改为我想要的数字,例如
对于 x=-7.00 和从 y=58.1 到 63.5 的变量 y 然后将第 4 列更改为 2 (或 3 或 4)
我想到了一些事情,但我不知道如何表达我提到的标准,然后写一个具有相同格式但新标志的新文件。
from numpy import *
fname='put the name here'
a='' #x-coordinates
b='' #y-coordinates
data = loadtxt("battri.node")
nodes=data[:,0]
x=data[:,1]
y=data[:,2]
flag=data[:,3]
for x=a:
for y=>b:
?????? I believe here i have to set the criterion but I cant find the correct expression
fid= open(fname+'_2.node','a')
fid.write('')
请您参考如下方法:
您可以避免 for 循环并使用 NumPy 花式索引应用标准来获得更好的性能(编辑 2:我将 x==-7.00 替换为基于公差的标准):
TOL = 0.001
crit1 = (abs((abs(x)-7.00))<TOL) & (y>=58.1) & (y<63.5)
flag[crit1] = 2
...
应用所有条件后,您可以直接打印 data,因为 x、y、z 和 flag 实际上是原始二维数组的 View data:
np.savetxt('output_file_name', data)
编辑:完整代码的示例:
from numpy import *
a='' #x-coordinates
b='' #y-coordinates
data = loadtxt("battri.node")
nodes=data[:,0]
x=data[:,1]
y=data[:,2]
flag=data[:,3]
crit1 = (x==-7.00) & (y>=58.1) & (y<63.5)
flag[crit1] = 2
savetxt('output_file_name', data)
