ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 17.04.2021

Просмотров: 3736

Скачиваний: 3

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.
background image

Introduction to Python for Science, Release 0.9.23

Out[33]:

array([

-

1.000e+00

,

-

9.506e-01

,

-

8.083e-01

,

-5.869e-01, -3.081e-01,

7.963e-04,

3.096e-01,

5.882e-01,

8.092e-01,

9.511e-01,

1.000e+00,

9.511e-01,

8.092e-01,

5.882e-01,

3.096e-01,

7.963e-04, -3.081e-01, -5.869e-01,

-8.083e-01, -9.506e-01, -1.000e+00])

You can use arrays as inputs for any of the functions introduced in the section on

Python

functions: a first look

You might well wonder what happens if Python encounters an

illegal operation. Here is one example.

In [34]:

a

Out[34]:

array([

-

1.

,

0.

,

1.

,

2.

,

3.

,

4.

,

5.

])

In [35]:

log(a)

-c:1: RuntimeWarning: divide by zero encountered in log

-c:1: RuntimeWarning: invalid value encountered in log

Out[35]:

array([

nan,

-

inf,

0.

,

0.693

,

1.099

,

1.386

,

1.609])

We see that NumPy calculates the logarithm where it can, and returns

nan

(not a number)

for an illegal operation, taking the logarithm of a negative number, and

-inf

, or

−∞

for

the logarithm of zero. The other values in the array are correctly reported. NumPy also
prints out a warning message to let you know that something untoward has occurred.

Arrays can also be added, subtracted, multiplied, and divided by each other on an element-
by-element basis, provided the two arrays have the same size. Consider adding the two
arrays

a

and

b

defined below:

In [36]:

a

=

array([

34.

,

-

12

,

5.

])

In [37]:

b

=

array([

68.

,

5.0

,

20.

])

In [38]:

a

+

b

Out[38]:

array([

102.

,

-

7.

,

25.

])

The result is that each element of the two arrays are added. Similar results are obtained
for subtraction, multiplication, and division:

In [39]:

a

-

b

Out[39]:

array([

-

34.

,

-

17.

,

-

15.

])

In [40]:

a

*

b

Out[40]:

array([

2312.

,

-

60.

,

100.

])

40

Chapter 3. Strings, Lists, Arrays, and Dictionaries


background image

Introduction to Python for Science, Release 0.9.23

In [41]:

a

/

b

Out[41]:

array([

0.5

,

-

2.4

,

0.25

])

These kinds of operations with arrays are called

vectorized

operations because the entire

array, or “vector”, is processed as a unit. Vectorized operations are much faster than pro-
cessing each element of arrays one by one. Writing code that takes advantage of these
kinds of vectorized operations is almost always to be preferred to other means of accom-
plishing the same task, both because it is faster and because it is usually syntactically
simpler. You will see examples of this later on when we discuss loops in Chapter 6.

3.3.3 Slicing and addressing arrays

Arrays can be sliced in the same ways that strings and lists can be sliced—any way you
slice it! Ditto for accessing individual array elements: 1-d arrays are addressed the same
way as strings and lists. Slicing, combined with the vectorized operations can lead to
some pretty compact and powerful code.

Suppose, for example, that we have two arrays

y

, and

t

for position

vs

time of a falling

object, say a ball, and we want to use these data to calculate the velocity as a function of
time:

In [42]:

y

=

array([

0.

,

1.3

,

5.

,

10.9

,

18.9

,

28.7

,

40.

])

In [43]:

t

=

array([

0.

,

0.49

,

1.

,

1.5

,

2.08

,

2.55

,

3.2

])

We can get find the average velocity for time interval

i

by the formula

v

i

=

y

i

y

i

1

t

i

t

i

1

We can easily calculate the entire array of of velocities using the slicing and vectorized
subtraction properties of NumPy arrays by noting that we can create two

y

arrays dis-

placed by one index

In [44]:

y[:

-

1

]

Out[44]:

array([

0.

,

1.3

,

5.

,

10.9

,

18.9

,

28.7

])

In [45]:

y[

1

:]

Out[45]:

array([

1.3

,

5.

,

10.9

,

18.9

,

28.7

,

40.

])

The element-by-element difference of these two arrays is

3.3. NumPy arrays

41


background image

Introduction to Python for Science, Release 0.9.23

In [46]:

y[

1

:]

-

y[:

-

1

]

Out[46]:

array([

1.3

,

3.7

,

5.9

,

8.

,

9.8

,

11.3

])

The element-by-element difference of the two arrays

y[1:]-y[:-1]

divided by

t[1:]-t[:-1]

gives the entire array of velocities

In [47]:

v

=

(y[

1

:]

-

y[:

-

1

])

/

(t[

1

:]

-

t[:

-

1

])

In [48]:

v

Out[48]:

array([

2.65306122

,

7.25490196

,

11.8

,

13.79310345,

20.85106383,

17.38461538])

Of course, these are the average velocities over each interval so the times best associated
with each interval are the times halfway in between the original time array, which we can
calculate using a similar trick of slicing:

In [49]:

tv

=

(t[

1

:]

+

t[:

-

1

])

/

2.

In [50]:

tv

Out[50]:

array([

0.245

,

0.745

,

1.25

,

1.79

,

2.315

,

2.875

])

3.3.4 Multi-dimensional arrays and matrices

So far we have examined only one-dimensional NumPy arrays, that is, arrays that consist
of a simple sequence of numbers. However, NumPy arrays can be used to represent
multidimensional arrays. For example, you may be familiar with the concept of a

matrix

,

which consists of a series of rows and columns of numbers. Matrices can be represented
using two-dimensional NumPy arrays. Higher dimension arrays can also be created as
the application demands.

Creating NumPy arrays

There are a number of ways of creating multidimensional NumPy arrays. The most
straightforward way is to convert a list to an array using NumPy’s

array

function, which

we demonstrate here:

In [51]:

b

=

array([[

1.

,

4

,

5

], [

9

,

7

,

4

]])

In [52]:

b

Out[52]:

array([[

1.

,

4.

,

5.

],

[9., 7., 4.]])

42

Chapter 3. Strings, Lists, Arrays, and Dictionaries


background image

Introduction to Python for Science, Release 0.9.23

Notice the syntax used above in which two one-dimensional lists

[1., 4, 5]

and

[9,

7, 4]

are enclosed in square brackets to make a two-dimensional list. The

array

function converts the two-dimensional list, a structure we introduced earlier, to a two-
dimensional array. When it makes the conversion from a list to an array, the array function
makes all the elements have the same data type as the most complex entry, in this case
a float. This points out an important difference between NumPy arrays and lists: all
elements of a NumPy array must be of the same data type: floats, or integers, or complex
numbers,

etc

.

There are a number of other functions for creating arrays. For example, a 3 row by 4
column array or

3

×

4

array with all the elements filled with 1 can be created using the

ones

function introduced earlier.

In [53]:

a

=

ones((

3

,

4

), dtype

=

float

)

In [54]:

a

Out[54]:

array([[

1.

,

1.

,

1.

,

1.

],

[ 1., 1., 1., 1.],

[ 1., 1., 1., 1.]])

Using a tuple to specify the size of the array in the first argument of the

ones

function

creates a multidimensional array, in this case a two-dimensional array with the two ele-
ments of the tuple specifying the number of rows and columns, respectively. The

zeros

function can be used in the same way to create a matrix or other multidimensional array
of zeros.

The

eye(N)

function creates an

N

×

N

two-dimensional identity matrix with ones along

the diagonal:

In [55]:

eye(

4

)

Out[55]:

array([[

1.

,

0.

,

0.

,

0.

],

[ 0., 1., 0., 0.],

[ 0., 0., 1., 0.],

[ 0., 0., 0., 1.]])

Multidimensional arrays can also be created from one-dimensional arrays using the

reshape

function. For example, a

2

×

3

array can be created as follows:

In [56]:

c

=

arange(

6

)

In [57]:

c

Out[57]:

array([

0

,

1

,

2

,

3

,

4

,

5

])

In [58]:

c

=

reshape(c, (

2

,

3

))

3.3. NumPy arrays

43


background image

Introduction to Python for Science, Release 0.9.23

In [59]:

c

Out[59]:

array([[

0

,

1

,

2

],

[3, 4, 5]])

Indexing multidimensional arrays

The individual elements of arrays can be accessed in the same way as for lists:

In [60]:

b[

0

][

2

]

Out[60]:

5.

You can also use the syntax

In [61]:

b[

0

,

2

]

Out[61]:

5.

which means the same thing. Caution: both the

b[0][2]

and the

b[0,2]

syntax work

for NumPy arrays and mean exactly the same thing; for lists only the

b[0][2]

syntax

works.

Matrix operations

Addition, subtraction, multiplication, division, and exponentiation all work with multidi-
mensional arrays the same way they work with one dimensional arrays, on an element-
by-element basis, as illustrated below:

In [62]:

b

Out[62]:

array([[

1.

,

4.

,

5.

],

[ 9., 7., 4.]])

In [63]:

2

*

b

Out[63]:

array([[

2.

,

8.

,

10.

],

[ 18., 14.,

8.]])

In [64]:

b

/

4.

Out[64]:

array([[

0.25

,

1.

,

1.25

],

[ 2.25, 1.75, 1.

]])

In [65]:

b

**

2

Out[65]:

array([[

1.

,

16.

,

25.

],

[ 81., 49., 16.]])

In [66]:

b

-

2

44

Chapter 3. Strings, Lists, Arrays, and Dictionaries