1

I want to convert the array A containing string elements to list. But I am running into error while using split(). I present the expected output.

import numpy as np
from numpy import nan
A=np.array(['[1]', '[2]',  '[3]', '[4]', '[5]'])
A.split()
print(A)

The error is

in <module>
    A.split()

AttributeError: 'list' object has no attribute 'split'

The expected output is

array([[1], [2], [3], [4], [5]])
2
  • 1
    Try this: A = np.array([eval(e) for e in A]) Commented Sep 11, 2022 at 16:20
  • A string has a split method, not a list! Commented Sep 11, 2022 at 16:20

2 Answers 2

2

I think this should work

A=np.array(['[1]', '[2]',  '[3]', '[4]', '[5]'])
output = [[int(a.strip("[|]"))] for a in A]
print(output)
[[1], [2], [3], [4], [5]]

if you prefer just an list, instead of a list of list

A=np.array(['[1]', '[2]',  '[3]', '[4]', '[5]'])
output = [int(a.strip("[|]")) for a in A]
print(output)
[1, 2, 3, 4, 5]
Sign up to request clarification or add additional context in comments.

3 Comments

The output I am getting with your code is [array(['[1]', '[2]', '[3]', '[4]', '[5]'], dtype='<U3')].
I have edited the the code if you print output is impossible you are getting this. Things apart I don't get why you are using numpy to have an array of strings.
I think you are printing A and not output. A is the array you have as input, output is what you want
0
import numpy as np
A = np.array(['[1]', '[2]',  '[3]', '[4]', '[5]'])
B = np.array([int(item.strip("'\'").replace("[","").replace("]","")) for item in A] )
print(B) #[1 2 3 4 5]

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.