pythonnumpynumpy-dtype

How to define the length of a string in an array


I'm defining an array that will receive many lines of text with between 30 and 40 characters :

portfolio_names = np.empty((30000,1)).astype("str")

When I run my program, I see that there is a truncation at 32 characters, which causes me an issue. How do I define my array so that it accepts more than 32 characters? Or any workaround as well? Thank you


Solution

  • To create an array of 40-character unicode strings, you can use the dtype "40str" (where str is treated equivalently to the typecode U):

    portfolio_names = np.empty((30000,1), dtype="40str")