简体   繁体   中英

How to create a 2D numpy array from a block of strings

With list comprehension, I am able to take a 20x20 block of numbers in string format, and convert it to a list of lists of integers. The numbers are seperated by white space and the lines are seperated by a newline.

grid = [[int(x) for x in line.split()] for line in nums.split('\n')]

However, what I want is to use numpy for its speed. I could use np.asarray() with my intermediate list, but I don't think that is efficient use of numpy.

I also tried using np.fromstring() , but I can't figure out the logic to make it work for a 2D array.

Is there any way to accomplish this task without the use of creating intermediate python lists?

You could use np.fromstring setting a space as separator and reshape to the desired shape:

np.fromstring(s, sep=' ').reshape(20, 20)

Or as a more general solution, following @mihammad's solution:

rows = s.count('\n') + 1
np.fromstring(s, sep=' ').reshape(-1, rows)

More general for any 2D grid:

rows = s.count('\n') + 1
np.fromstring(s, sep=' ').reshape(rows, -1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM