0

Below is my code:

import numpy as np

row_length = 5
col_length = 3
x = np.empty([row_length,col_length],dtype=str) 
x[1,2]='ddd'
print(x)

and the result is:

[['' '' '']
 ['' '' 'd']
 ['' '' '']
 ['' '' '']
 ['' '' '']]

why? The result I expected is:

[['' '' '']
 ['' '' 'ddd']
 ['' '' '']
 ['' '' '']
 ['' '' '']]

Who can tell me how to fix it?

0

1 Answer 1

1

Your issue is that dtype=str defaults to strings of length 1. Fix it by specifying the max length:

import numpy as np
row_length = 5
col_length = 3

# Specify the maximum string length (e.g., 10 characters)
x = np.empty([row_length, col_length], dtype='<U10') 
x[1, 2] = 'ddd'
print(x)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.