Reputation: 83
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()
Upvotes: 1
Views: 3414
Reputation: 8689
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
Upvotes: 1
Reputation: 28868
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')
Upvotes: 0