Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string push values in 2D Array

Tags:

python

numpy

I want to parse a string of numbers into a two-dimensional square array/matrice the first digit identifies the size of of the matrice for example

Input 45621797533863034 Here first digit 4 identifies its 4x4 matrice and rest are the values.

so array should be

5 6 2 1
7 9 7 5
3 3 8 6
3 0 3 4
like image 468
Faqahat Fareed Avatar asked Dec 18 '25 16:12

Faqahat Fareed


1 Answers

IIUC:

s = '45621797533863034'
s = np.array(list(s))
s[1:].reshape(int(s[0]), -1)

Output:

array([['5', '6', '2', '1'],
       ['7', '9', '7', '5'],
       ['3', '3', '8', '6'],
       ['3', '0', '3', '4']], dtype='<U1')

If you want the output to be numeric, you can pass in the correct dtype:

s = '45621797533863034'
s = np.array(list(s), dtype=np.uint8)
s[1:].reshape(s[0],-1)

Output:

array([[5, 6, 2, 1],
       [7, 9, 7, 5],
       [3, 3, 8, 6],
       [3, 0, 3, 4]], dtype=uint8)
like image 74
Quang Hoang Avatar answered Dec 20 '25 05:12

Quang Hoang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!