user
user

Reputation: 71

Convert a string of float arrays into an ndarray

Imagine one has to convert an ndarray into a string, then he has to convert the string back into an ndarray. For example, you have this string:

[1.1463377809323188, -5.631205546574898, 2.2669977232047676][4.579898563059968, 7.903827618691004, -6.286433358859447]

How could one conver this into an ndarray like so:

[[ 1.14633778 -5.63120555  2.26699772]
 [ 4.57989856  7.90382762 -6.28643336]]

I was thinking of converting the str into a list, then convert the list into an ndarray. However, the str.split() method yield me this:

['[1.1463377809323188,', '-5.631205546574898,', '2.2669977232047676][4.579898563059968,', '7.903827618691004,', '-6.286433358859447]']

When I try split('[]') now i'm left with only one element in the list:

['[2.182687926670855, -6.165595264315509, 2.0514527771233135][-1.9916686860482642, 6.353279016100898, -2.237430822379459]']

Upvotes: 0

Views: 40

Answers (1)

not_speshal
not_speshal

Reputation: 23166

This would work:

string = "[1.1463377809323188, -5.631205546574898, 2.2669977232047676][4.579898563059968, 7.903827618691004, -6.286433358859447]"
>>> [[float(x.strip()) for x in row.replace("[","").split(",")] for row in string.split("]") if len(row.strip())>0]
[[1.1463377809323188, -5.631205546574898, 2.2669977232047676],
 [4.579898563059968, 7.903827618691004, -6.286433358859447]]

Upvotes: 1

Related Questions