0

I have a list of Strings

    ls = ["1 , abc , 3.3" , "1 , def , 3.245" , "1 , ghi , 9.34"]

which I have to convert into a 3x3 numpy array with appropriate data types i.e convert to

    array([[1, 'abc', 3.3],
           [1, 'def', 3.245],
           [1, 'ghi', 9.34]])

I am currently using the following code to convert the list of strings into an array :

    new_array = np.array([i.split(' , ') for i in ls])

but the result I get is :

    array([['1', 'abc', '3.3'],
           ['1', 'def', '3.245'],
           ['1', 'ghi', '9.34']])

and using the following code to typecast :

    new_arr[:,0] = new_arr[:,0].astype(int)
    new_arr[:,1] = new_arr[:,1].astype(str)
    new_arr[:,2] = new_arr[:,0].astype(float)

How can I get the desired array with the specific data types ?

4
  • 4
    Possible duplicate of Converting list of lists to numpy array with multiple data types Commented Dec 20, 2017 at 12:03
  • @kabanus that solution gives out a list of tuples, I need a 2D array Commented Dec 20, 2017 at 13:58
  • Then this can't be done as far as I know - it doesn't make sense in some sense (funny). A Numpy array is really just a C matrix in a sense, so it really 'ought' to hold a single datatype (hence you get a list of tuples - a single complex type). I think this is an XY problem - post what you actually want to do, and why you need this array. In any case a pandas dataframe is more suited to this type of table object. Commented Dec 20, 2017 at 14:13
  • In case you don't have an XY problem, you should consider looking at the pandas module. Dataframes would give you the option to index your data in 2d, and of course a whole lot of data-based machinery around it. And almost certainly you could read your input conveniently into a dataframe, without creating that list of yours in the first place. Commented Dec 20, 2017 at 23:55

0

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.