0

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]']
1
  • Why convert to a string at all? Commented Jul 14, 2021 at 16:02

1 Answer 1

1

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.