I have a simple question with Python numpy. I have a numpy array as follows.

a = [ [1000 2 3]
            [4 5000 6]
            [7 8 9000] ]

I want to be able to print 3 slices of the array to a txt file so that the elements in the column line up.

For example, I would like to write a loop

for i in range(0,3):
       print a[i,:]

and have the txt file have all the elements lined up.
1000 2 3
4 5000 6
7 8 9000

I looked at numpy.savetxt but didn't see any print formatting(like printf) option. I also redirected my output stream to a file with

sys.stdout = open("file.txt", "w")

and used print statements but didn't know how to format a data slice(a[i,:]).

sys.stdout = open("file.txt", "w")
for i in range(0,3):
  print x[i,:]?? how to do print format here

Can anyone help me? Thanks.

Recommended Answers

All 2 Replies

put in line 3

print ''.join('%8i' % value for value in a[i])

That is older formatting c-style, as you seem familiar with it.
(untested from mobile but prinsiple should be right)

How did you get such a srtange looking numpy array?
How will Python know that this is supposed to be a numpy array type?

Generally ...

# Python list to numpy array and then text string

import numpy as np

mylist = [
[1000, 2, 3],
[4, 5000, 6],
[7, 8, 9000]
]

# create a numpy array from a corresponding Python list object
np_arr = np.array(mylist)

print(np_arr)

''' result ...
[[1000    2    3]
 [   4 5000    6]
 [   7    8 9000]]
'''

# np.array_str(a, max_line_width=None, precision=None, suppress_small=None) 
# convert to a text string
arr_str = np.array_str(np_arr)

sf = """
Include the array into a text string
%s
"""
print(sf % arr_str)

''' result ...
Include the array into a text string
[[1000    2    3]
 [   4 5000    6]
 [   7    8 9000]]
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.