Python Forum

Full Version: filling and printing numpy arrays of str
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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')
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
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)
Thank you, that helps me a lot.

I will mark this thread as solved now.

Peter