简体   繁体   中英

How to write a dictionary with numpy array in a file

I have a dictionary like this: `

d = {1: array([ 1.,  1., 0., 1.]),2: array([ 0.,  1., 0., 1.]), 3:
        array([ 1.,  0., 0., 1.]), 4: array([ 1.,  0., 1., 1.])}`

I want to write all the values:

 ([ 1.,  1., 0., 1.], [ 0.,  1., 0., 1.], 
  [ 1.,  0., 0., 1.], [ 1.,  0., 1., 1.]) 

in a .tsv file. Each value in a column, in this example I would have 4 columns with 4 rows.

This is what I want in the file:

1 0 1 1

1 1 0 0

0 0 0 1

1 1 1 1

each numpy array is printed in a different column.

The code that I have gives me all values in the same column:

f = open("Result.tsv", "wb")
for key, value in d.items():
    np.savetxt(f, value, delimiter=',')
f.close()

Simplest way might be to format your array to be 2d rather than a dict of 1d columns:

out = np.empty((4, 4))
for colnb, col in d.items():
    out[:, colnb-1] = col
with open("Result.tsv", 'wb') as f:
    np.savetxt(f, out, delimiter=',')

This way, you let the numpy savetxt function handle all the work

This gives you almost what you wanted:

with open('Result.csv', 'w') as f:
    for k, v in d.items():
        f.write(str(v)[1:-1]+'\n')



$ cat Result.csv
 1.  1.  0.  1.
 0.  1.  0.  1.
 1.  0.  0.  1.
 1.  0.  1.  1.

This goes the extra step and removes the decimal point:

with open('Result.csv', 'w') as f:
    for k, v in d.items():
        f.write(str(map(int, v))[1:-1]+'\n')

Note also that if you are already writing this as a binary file, which is input for another program you can do the following (but this does not give you the text format you showed). And finally you do this:

with open('Result.csv', 'w') as f:
    for k, v in d.items():
        v.tofile(f, sep=',', format='%d')
        f.write('\n')       

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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