0
votes

I have written this code to make an array=>

import numpy as np
a = np.array([[[1,3],[1,4]],[[1,4],[6,9]]])
np.savetxt('test.txt',a,fmt='%d')

and getting this error =>

Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/numpy-1.11.2-py3.4-linux-x86_64.egg/numpy/lib/npyio.py", line 1158, in savetxt fh.write(asbytes(format % tuple(row) + newline)) TypeError: %d format: a number is required, not numpy.ndarray

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.4/dist-packages/numpy-1.11.2-py3.4-linux-x86_64.egg/numpy/lib/npyio.py", line 1162, in savetxt % (str(X.dtype), format)) TypeError: Mismatch between array dtype ('int64') and format specifier ('%d %d')

How to save the array as an integer in file using numpy?

3
what kind of structure are you expecting for your output file? can you post what you want?Astrom
@roganjosh I want to save that matrix in that txt fileSudip Das
you have a 3d array, try save a.reshape(-1, 2) instead. np.savetxt('test.txt',a.reshape(-1,2),fmt='%d')Psidom
okk thanks for helping me. perfect @PsidomSudip Das

3 Answers

1
votes

There is an old thread on this problem

Saving numpy array to csv produces TypeError Mismatch

If you check, your array is a 3D array which is causing the issue

1. If you translate it to a 2D it will work

import numpy as np a = np.array([[[1,3],[1,4]],[[1,4],[6,9]]]) np.savetxt('test.txt',a.reshape(-1,a.shape[-1]),fmt="%d")

2. If you write one row at a time it will work too

But this will have issues reading back

My suggestion, write it as dict/json and convert it to numpy after reading

2
votes

I am not sure what kind of output you want...

You can do this

F = open('test.txt', 'w')
for i in a:
    for j in i:
        line = '%s \t %s \n'%(j[0], j[1])
        F.write(line)

F.close()

Will give you

1 3

1 4

1 4

6 9

1
votes
%d format: a number is required, not numpy.ndarray

Essentially you can't use a format string on an object/class/what-have-you; its expecting a number, not an array of numbers

convert the array to a printable string. Similarly, you can't really save integers in files, only strings in files.

What you'll want to do is take each row in the array and write it to the file, something similar to this:

to_write = ''
for small_list in list_of_lists:
    to_write += ''.join(small_list, ',') + "\n"
my_file.write(to_write)