简体   繁体   English

将ndarray保存到文本文件的麻烦

[英]trouble with saving ndarray to text file

I have a set of data in the format as below: 我有一组数据,格式如下:

name q1 q2 q3 名称q1 q2 q3
ER_1 0 0 0 ER_1 0 0 0
ER_2 0 0 0 ER_2 0 0 0

I have written a code that does a calculation by reading in this data table and then if the particular calculation concerns one of the names mentioned ex: ER_1 then the q1, q2 and q3 will get updated. 我编写了一个代码,该代码通过读取此数据表来进行计算,然后,如果特定的计算涉及例如提到的名称之一:ER_1,则q1,q2和q3将得到更新。 I am able to do this and modify the table except that I have trouble saving it in the same format. 我可以执行此操作并修改表,但无法将其保存为相同格式。 Here is my attempt which results in a txt file with all elements in a single line ie : name,q1,q2,q3,ER_1,0,0,0,ER_2,0,0,0 这是我的尝试,导致一个txt文件中所有元素都位于一行中,即:name,q1,q2,q3,ER_1,0,0,0,ER_2,0,0,0

data=numpy.loadtxt('table.txt', dtype=str,usecols=(0,1,2,3,4))#,unpack=True)

NAME='ER_1'

lst=[0,1,2]

for i in lst:
    if NAME in data[i][0]:
        data[i][1] = '27'


data.tofile('newdata.txt',sep=',')

该图像与给出的第一个建议有关

code as requested: 要求的代码:

so you'll need to make a text file called - massout.txt which looks like this: 因此,您需要制作一个名为-massout.txt的文本文件,如下所示:

Source   M_ratio  R_ratio   B_ratio   F_tot F_red   F_blue  c3
ER_1     0           0      0         0       0        0     0 
ER_2     0           0      0         0       0        0     0     

then just copy and run this: 然后只需复制并运行:

massout=numpy.loadtxt('massout.txt', dtype=str,usecols=(0,1,2,3,4,5,6,7))#,unpack=True)
source='ER_1'

lst=[0,1,2]

for i in lst:
    if source in massout[i][0]:
        massout[i][1] = '27'


numpy.savetxt('newdata.txt', massout, delimiter='', fmt='%s\n'  )

The tofile method writes the data "flattened". tofile方法将数据“展平”。 It writes the elements sequentially to the file, losing any shape information about the array. 它将元素顺序写入文件,丢失有关数组的任何形状信息。

Your use of the function numpy.savetxt needs a couple tweaks. 您对numpy.savetxt函数的numpy.savetxt需要进行一些调整。 To separate the fields with spaces, use delimiter=' ' (that's a space character, not an empty string). 要用空格delimiter=' '字段,请使用delimiter=' ' (这是一个空格字符,而不是一个空字符串)。 Don't include '\\n' in the fmt argument. 不要在fmt参数中包含'\\n' The following works for me: 以下对我有用:

numpy.savetxt('newdata.txt', massout, delimiter=' ', fmt='%s')

PS With a 2-d numpy array, it is more efficient and stylistically preferable to index the array as massout[i, j] instead of massout[i][j] . PS对于massout[i, j] numpy数组,将数组索引为massout[i, j]而不是massout[i][j]更为有效,从风格上也更可取。 That is, you should write 也就是说,你应该写

    massout[i, 1] = '27'

instead of 代替

    massout[i][1] = '27'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM