21

I have tuple of lists. One of these lists is a list of scores. I want to convert the list of scores to a numpy array to take advantage of the pre-built stats that scipy provides.

In this case the tuple is called 'data'

In [12]: type data[2]
-------> type(data[2])
Out[12]: <type 'list'>

In [13]: type data[2][1]
-------> type(data[2][1])
Out[13]: <type 'list'>

In [14]: type data[2][1][1]
-------> type(data[2][1][1])
Out[14]: <type 'float'>

In [15]: print data[2][1]
-------> print(data[2][1])
[16.66, 16.66, 16.66, 16.66, 5.5599999999999996, 16.699999999999999]

In [16]: print data[2][1][1]
-------> print(data[2][1][1])
16.66

Can I do this easily once I have stored the tuple?

1 Answer 1

47

The command numpy.asarray will turn a number of pre-set iterable containers (list, tuple, etc) into a numpy array.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 for numpy.asarray it's very powerful, just a note. does it return a deep copy or simply another view of the input array?
@linello: It copies if it has to, such as when the input is a Python built-in sequence type.
Nope, that does not always work, thus -1. E.g. x = np.asarray((1,2,3,4,5))
Haha, this question and answer are both 11 years old! @Imago On numpy 1.19.2 and python 3.10, as well as the very early version of numpy here, asarray does work for tuples: your test code gives me a numpy array. What error are you seeing?

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.