Convert strings within an array to list in Python

Question:

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]])
Asked By: user19862793

||

Answers:

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]
Answered By: Lucas M. Uriarte
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]
Answered By: uozcan12
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.