Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)
edited by

I have below following 3 numpy arrays in the python file:

array([[    1,     1,    14,     1,    15],

       [    2,     1,    14,     1,    13],

       [    3,     1,    15,     1,    13]]) 

array([[   1,    1,    1,   13],

       [   2,    1,    1,   14],

       [   3,    1,    1,   15]])

array([[  10,    2,    4,   17],

       [  11,    3,    6,   20],

       [  12,    4,    6,   21]])

I am trying to output the text file with spaces and words in between them. So my output would look like this:

ListA

1 1 14 1 15

2 1 14 1 13

3 1 15 1 13

ListB

1 1 1 13

2 1 1 14

3 1 1 15

ListC

10 2 4 17

11 3 6 20

12 4 6 21

There are arrays of thousand rows long, so it has to be scalable. Right now, I am using NumPy to save my text command and manually adding the space and headers in between my arrays.

1 Answer

0 votes
by (36.8k points)

Code:

import re

txt = '''

array([[    1,     1,    14,     1,    15],

       [    2,     1,    14,     1,    13],

       [    3,     1,    15,     1,    13]]) 

array([[   1,    1,    1,   13],

       [   2,    1,    1,   14],

       [   3,    1,    1,   15]])

array([[  10,    2,    4,   17],

       [  11,    3,    6,   20],

       [  12,    4,    6,   21]])

'''

txt = txt.replace('array([[', 'ListA\n', 1)

txt = txt.replace('array([[', 'ListB\n', 1)

txt = txt.replace('array([[', 'ListC\n', 1)

txt = re.sub('[\[\]\),]', '', txt)

txt = re.sub(' +', ' ', txt)

print(txt)

Output:

ListA

 1 1 14 1 15

 2 1 14 1 13

 3 1 15 1 13

ListB

 1 1 1 13

 2 1 1 14

 3 1 1 15

ListC

 10 2 4 17

 11 3 6 20

 12 4 6 21

Want to be a Data Science expert? Come and join this Data Science Courses

Browse Categories

...