简体   繁体   中英

python data analysis, difficulty understanding cookbook code

I'm learning to use python for data analysis, etc. and I am a little confused about what is going on in this code from the scipy cookbook .

When the cookbook describes the integration and then plotting process, via matplotlib, it has first:

t = linspace(0, 15, 1000)
X0 = array([10,5])
X = scipy.integrate.odeint(dX_dt, X0, t)
rabbits, foxes = X.T

What does this code do?

rabbits, foxes = X.T

Specifically, what does XT do?

XT is the transpose of X . So, in that line, X must be an array with shape (N,2) . When you transpose it you get an array of shape (2,N) which can be unpacked.

Consider:

>>> import numpy as np
>>> a = np.arange(10).reshape((5,2))
>>> a
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])
>>> B,C = a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>> B,C = a.T
>>> B
array([0, 2, 4, 6, 8])
>>> C
array([1, 3, 5, 7, 9])

Also note that wherever possible , the transpose will return a new view (the data won't be copied), so this is a very efficient operation.

T stands for transpose. So X is aligned such that rabbits gets assigned to the first element and foxes to the second. These are arrays (equivalent to matrices in linear algebra) not lists, so that alignment does matter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM