Python Forum
filling and printing numpy arrays of str - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: filling and printing numpy arrays of str (/thread-27443.html)



filling and printing numpy arrays of str - pjfarley3 - Jun-07-2020

I am new to python but experienced in several other languages. I do not understand yet why numpy.full does not fill an array of strings with the string value I supply in the code.

Example code and output follows. OS is Win10-64 Pro, Python version is 3.8.3.

#!/usr/bin/env python
import numpy as np

class arstr:
    def __init__(self, asize, aval):
        self.strs = np.full([asize, asize, asize], aval, dtype=str)

Mystrs = arstr(3, " ? ")

for s in Mystrs.strs:
    print (s)

exit()
Output in a cmd.exe window follows.

Output:
C:\Testdir>python atest.py [[' ' ' ' ' '] [' ' ' ' ' '] [' ' ' ' ' ']] [[' ' ' ' ' '] [' ' ' ' ' '] [' ' ' ' ' ']] [[' ' ' ' ' '] [' ' ' ' ' '] [' ' ' ' ' ']]
Why are each of the array elements a single blank character and not the three-character string " ? " that I specified in the invocation of the class?

Thank you in advance for any help you can offer.

Peter


RE: filling and printing numpy arrays of str - bowlofred - Jun-07-2020

dtype=strmeans a fixed-size string. And without other information, it defaults to a one-character string. So your info is being truncated to the first character.

You can instead pass a tuple, with the padded size given as the second field.

>>> np.full([3], "ABC", dtype=(str))
array(['A', 'A', 'A'], dtype='<U1')
>>> np.full([3], "ABC", dtype=(str, 3))
array(['ABC', 'ABC', 'ABC'], dtype='<U3')



RE: filling and printing numpy arrays of str - pjfarley3 - Jun-07-2020

Thanks for that clarification. That cures at least a little my ignorance.

Is there a way to populate a numpy.ndarray with strings of arbitrary size?

Peter


RE: filling and printing numpy arrays of str - bowlofred - Jun-07-2020

It is possible to use the object type instead. Now instead of storing the data within the array, the array only stores references to external objects.

>>> x=np.full([3], "ABC")
>>> x[1] = "Longerstring"
>>> x
array(['ABC', 'Lon', 'ABC'], dtype='<U3') #note truncation

>>> x=np.full([3], "ABC", dtype=object)
>>> x[1] = "Longerstring"
>>> x
array(['ABC', 'Longerstring', 'ABC'], dtype=object)



RE: filling and printing numpy arrays of str - pjfarley3 - Jun-07-2020

Thank you, that helps me a lot.

I will mark this thread as solved now.

Peter