Instead of splitting and filtering, you could use np.fromstring:

>>> np.fromstring(b, sep='\t').reshape(-1, 4)
array([[ 191.25 ,    0.   ,    0.   ,    1.   ],
       [ 191.251,    0.   ,    0.   ,    1.   ],
       [ 191.252,    0.   ,    0.   ,    1.   ]])

This always returns a 1D array so reshaping is necessary.

Alternatively, to avoid reshaping, if you already have a string of bytes (as strings are in Python 2), you could use np.genfromtxt (with the help of the standard library's io module):

>>> import io
>>> np.genfromtxt(io.BytesIO(b))
array([[ 191.25 ,    0.   ,    0.   ,    1.   ],
       [ 191.251,    0.   ,    0.   ,    1.   ],
       [ 191.252,    0.   ,    0.   ,    1.   ]])

genfromtxt handles missing values, as well as offering much more control over how the final array is created.

Answer from Alex Riley on Stack Overflow
Top answer
1 of 5
26

The challenge is to save not only the data buffer, but also the shape and dtype. np.fromstring reads the data buffer, but as a 1d array; you have to get the dtype and shape from else where.

In [184]: a=np.arange(12).reshape(3,4)

In [185]: np.fromstring(a.tostring(),int)
Out[185]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

In [186]: np.fromstring(a.tostring(),a.dtype).reshape(a.shape)
Out[186]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

A time honored mechanism to save Python objects is pickle, and numpy is pickle compliant:

In [169]: import pickle

In [170]: a=np.arange(12).reshape(3,4)

In [171]: s=pickle.dumps(a*2)

In [172]: s
Out[172]: "cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I3\nI4\ntp6\ncnumpy\ndtype\np7\n(S'i4'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'<'\np11\nNNNI-1\nI-1\nI0\ntp12\nbI00\nS'\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x0c\\x00\\x00\\x00\\x0e\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x12\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\x16\\x00\\x00\\x00'\np13\ntp14\nb."

In [173]: pickle.loads(s)
Out[173]: 
array([[ 0,  2,  4,  6],
       [ 8, 10, 12, 14],
       [16, 18, 20, 22]])

There's a numpy function that can read the pickle string:

In [181]: np.loads(s)
Out[181]: 
array([[ 0,  2,  4,  6],
       [ 8, 10, 12, 14],
       [16, 18, 20, 22]])

You mentioned np.save to a string, but that you can't use np.load. A way around that is to step further into the code, and use np.lib.npyio.format.

In [174]: import StringIO

In [175]: S=StringIO.StringIO()  # a file like string buffer

In [176]: np.lib.npyio.format.write_array(S,a*3.3)

In [177]: S.seek(0)   # rewind the string

In [178]: np.lib.npyio.format.read_array(S)
Out[178]: 
array([[  0. ,   3.3,   6.6,   9.9],
       [ 13.2,  16.5,  19.8,  23.1],
       [ 26.4,  29.7,  33. ,  36.3]])

The save string has a header with dtype and shape info:

In [179]: S.seek(0)

In [180]: S.readlines()
Out[180]: 
["\x93NUMPY\x01\x00F\x00{'descr': '<f8', 'fortran_order': False, 'shape': (3, 4), }          \n",
 '\x00\x00\x00\x00\x00\x00\x00\x00ffffff\n',
 '@ffffff\x1a@\xcc\xcc\xcc\xcc\xcc\xcc#@ffffff*@\x00\x00\x00\x00\x00\x800@\xcc\xcc\xcc\xcc\xcc\xcc3@\x99\x99\x99\x99\x99\x197@ffffff:@33333\xb3=@\x00\x00\x00\x00\x00\x80@@fffff&B@']

If you want a human readable string, you might try json.

In [196]: import json

In [197]: js=json.dumps(a.tolist())

In [198]: js
Out[198]: '[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]'

In [199]: np.array(json.loads(js))
Out[199]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

Going to/from the list representation of the array is the most obvious use of json. Someone may have written a more elaborate json representation of arrays.

You could also go the csv format route - there have been lots of questions about reading/writing csv arrays.


'[[ 0.5544  0.4456], [ 0.8811  0.1189]]'

is a poor string representation for this purpose. It does look a lot like the str() of an array, but with , instead of \n. But there isn't a clean way of parsing the nested [], and the missing delimiter is a pain. If it consistently uses , then json can convert it to list.

np.matrix accepts a MATLAB like string:

In [207]: np.matrix(' 0.5544,  0.4456;0.8811,  0.1189')
Out[207]: 
matrix([[ 0.5544,  0.4456],
        [ 0.8811,  0.1189]])

In [208]: str(np.matrix(' 0.5544,  0.4456;0.8811,  0.1189'))
Out[208]: '[[ 0.5544  0.4456]\n [ 0.8811  0.1189]]'
2 of 5
11

I'm not sure there's an easy way to do this if you don't have commas between the numbers in your inner lists, but if you do, then you can use ast.literal_eval:

import ast
import numpy as np
s = '[[ 0.5544,  0.4456], [ 0.8811,  0.1189]]'
np.array(ast.literal_eval(s))

array([[ 0.5544,  0.4456],
       [ 0.8811,  0.1189]])

EDIT: I haven't tested it very much, but you could use re to insert commas where you need them:

import re
s1 = '[[ 0.5544  0.4456], [ 0.8811 -0.1189]]'
# Replace spaces between numbers with commas:
s2 = re.sub('(\d) +(-|\d)', r'\1,\2', s1)
s2
'[[ 0.5544,0.4456], [ 0.8811,-0.1189]]'

and then hand on to ast.literal_eval:

np.array(ast.literal_eval(s2))
array([[ 0.5544,  0.4456],
       [ 0.8811, -0.1189]])

(you need to be careful to match spaces between digits but also spaces between a digit an a minus sign).

🌐
Stack Overflow
stackoverflow.com › questions › 20625380 › convert-variable-string-to-array-2d
python 2.7 - Convert variable string to array 2d - Stack Overflow
This string form very similar to an encoded json string that by few change on this you can load this by json library, python code for converting this value to the 2D array is below:
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › convert-a-string-into-a-square-matrix-grid-of-characters
Convert a String into a square matrix grid of characters - GeeksforGeeks
September 18, 2022 - Given a string of length L. The task is to convert the string into a grid. Examples: Input : str = "haveaniceday" Output : have anic eday Explanation: k is the separator. If k is 4 then the output will be "have anic eday" Input :str = "geeksforgeeks" Output : geek sfor geek s ... Make a 2d character array of (rows * column) size.
🌐
GeeksforGeeks
geeksforgeeks.org › python-convert-string-to-matrix-having-k-characters-per-row
Python – Convert String to matrix having K characters per row | GeeksforGeeks
April 18, 2023 - ... The convertToMatrix function takes two arguments – a string test_str and an integer K. The goal of this function is to convert the input string into a 2D matrix where each row has K characters.
🌐
CSDN
devpress.csdn.net › python › 630458ecc67703293080b98a.html
How to read NumPy 2D array from string?_python_Mangs-Python
August 23, 2022 - string_to_arr("[[ 0.5544 0.4456], [ 0.8811 0.1189]]") should return the object array([[0.5544, 0.4456], [0.8811, 0.1189]]). Ideally arr_to_string would have a precision parameter that controlled the precision of floating points converted to strings, so that you wouldn't get entries like ...
🌐
Stack Overflow
stackoverflow.com › questions › 31209188 › how-to-convert-a-string-to-2d-array-in-python
How to Convert a String to 2d array in Python? - Stack Overflow
I am trying to implement the Columnar Transposition Algorithm in python. So I need to convert the input string to 2d array of characters. How do I do that?
🌐
Quora
quora.com › How-do-I-convert-a-1-dimensional-string-array-into-a-2D-string-array
How to convert a 1 dimensional string array into a 2D string array - Quora
Answer (1 of 3): You can not conevert one dimensional array into two dimenssional but you can change the way of storing data ..in two dimension array each element is at position i,j and in one dimensional each element it at i position where i and j are any interger values greater than 0 ..to do s...
🌐
Note.nkmk.me
note.nkmk.me › home › python
Convert 1D Array to 2D Array in Python (numpy.ndarray, list) | note.nkmk.me
May 15, 2023 - l = [0, 1, 2, 3, 4, 5] print(np.array(l).reshape(-1, 3).tolist()) # [[0, 1, 2], [3, 4, 5]] print(np.array(l).reshape(3, -1).tolist()) # [[0, 1], [2, 3], [4, 5]] source: numpy_1d_to_2d.py · See the following article on how to convert numpy.ndarray and list to each other. Convert numpy.ndarray and list to each other · If NumPy is not available, you can still achieve the transformation using list comprehensions, range(), and slices. List comprehensions in Python · How to use range() in Python · How to slice a list, string, tuple in Python ·