Python str, list, NumPy shard operations

Source: Internet
Author: User
Tags arithmetic operators scalar

In Python, tile operations are supported in the like String (str), list, tuple (tupple), and such sequence types

For an object slice, S is a string that can be used to get the characters in the string in the same way as an array index, and in the form of S[a:b:c], where s between A and B, with C as the interval, and the value of C as negative, and negative for the reverse value.

>>> s = ' bicycle ' >>> s[0] ' B ' >>> s[1] ' i ' >>> s[::3] ' bye ' >>> s[::-1] ' Elcycib ' >>> s[::-2] ' ECCB '

  

Assign a value to a slice

First, generate a list of length 16, from 0 to 15

>>> L = List (range) >>> l[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

  

Replace the value of index [2,5] with [20,30]

>>> L[2:5] = [5] >>> l[0, 1, 20, 30,, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

  

Index [5,8] will be deleted

>>> del l[5:8]>>> l[0, 1, 20, 30, 5, 9, 10, 11, 12, 13, 14, 15]

  

From the 9th index of the array, the [11,22] is assigned to the left Shard object in two units, and an error is given if the number of elements in the array and the number of elements in the Shard object are different.

>>> L[9::2] [15]>>> l[9::2] = [one, ten] >>> l[0, 1, ten, 5, 9, A, one, one, one, a, 22]> ;>> l[6::2][10, 66, 14]>>> l[6::2] = [  , 77, 88] The same, l[6::2] must be an array of [N1,N2,N3], if not, then Error >>> l[0, 1, 20, 30, 5, 9, 66, 11, 77, 11, 88, 22]

  

The result of list l[2:5] is [20, 30, 5], and our assignment is [30, 33], so 30 will replace 20,33 instead of 30, and 5 will be removed. If the number of elements in the left array is less than the number of elements in the assignment array, the elements after the original array fragment will be followed by the new element

>>> l[2:5][20, 5]>>> l[2:5] = [  9] >>> l[0, 1, a, a-I, a-I, a-one, one, one, one, one, one, 22]&G T;>> l[2:5][30, 9]>>> l[2:5] = [ -10, -20, -30, -40, -50]  >>> l[0, 1,-10,-20,-30,-40,- 50, 66, 11, 77, 11, 88, 22]

  

Copies a Shard object and modifies its values, and does not modify the values in the original list object

>>> L1 = l[2:5]>>> l1[-10, -20, -30]>>> l1 = [Ten, A, 30]>>> l1[10, 30]>>> ; L[0, 1,-10,-20,-30,-40,-50, 66, 11, 77, 11, 88, 22]

  

If a number is assigned to the Shard object on the left, an error is given

>>> L[2:5] =  Traceback (most recent):  File "<stdin>", line 1, in <module>typeerr Or:can Assign an iterable

  

  

NumPy Basic indexes and slices

>>> import NumPy as np>>> arr = Np.arange (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) >&G t;> arr[5]5>>> Arr[5:8]array ([5, 6, 7]) >>> Arr[5:8] =  # # Here's not going to get an error like before >>> Arrarray ([0,  1,  2,  3,  4,  8,  9])

  

As shown above, when you assign a scalar to a slice object (such as arr[5:8] = 12), the value is automatically propagated to the entire selection. The difference from the previous list of shards is that the NumPy array shard is the view of the original array, the data is not copied, and any modifications to the view are directly reflected on the source data, and if you do not want to modify the source data, use Arr[5:8].copy ():

>>> Arr_slice = arr[5:8]>>> Arr_slicearray ([[a]] >>> arr_slice[1] = 99>>> arr _slicearray ([0,  1,  2,  3,  4, 8,  9]) >>> Arrarray ([+] >> > arr_slice[:] = 66>>> Arrarray ([0,  1,  2,  3,  4,,,,  8,  9]) >>> Arr_slice_copy = Arr[5:8].copy () >>> Arr_slice_copyarray ([in [Up], [up]) >>> arr_slice_copy[:] = 88> >> Arr_slice_copyarray ([0,  1,  2,  3,  4, Arrarray,  A, A, 8,  9])

  

In a two-dimensional array, the elements at each index position are no longer scalar but one-dimensional arrays:

>>> arr2d = Np.array ([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> Arr2d[2]array ([7, 8, 9]) >>> Arr2d[0] [2]3>>> Arr2d[0, 2]3

  

To shard by rows or columns

>>> Arr2darray ([[1, 2, 3],       [4, 5, 6],       [7, 8, 9]]) >>> Arr2d[:2]  # Take the first two lines, that is, lines No. 0 and 1th Array ([[1, 2 , 3],       [4, 5, 6]]) >>> arr2d[:2, 1:]  # Take the first two rows after the 0th column all elements Array ([[[2, 3],       [5, 6]]) >>> arr2d[:, 1:2 ]  # takes the first column element of all rows (column index starting from 0) array ([[[2],       [5],       [8]]) >>> arr2d[1,: 2]  # takes the first two columns of element array ([4, 5]) >>> arr2d[2,: 1]  # Take the 0th column element of the second row array ([7]) >>> arr2d[:,: 1]  # take all rows of the 0th column element array ([[[1],       [4] ,       [7]]) >>> arr2d[:, 1:] = 0  # Similarly, the assignment of a shard expression spreads to the source data >>> Arr2darray ([[1, 0, 0],       [4, 0, 0] ,       [7, 0, 0]])

  

Boolean index

Let's say we have an array of data to store and an array of names (containing duplicates).

>>> import NumPy as np>>> from numpy.random import randint>>> names = Np.array ([' Bob ', ' Joe ', ' Bob ', ' 'll ', ' 'll ', ' Joe ', ' Joe ', ' Bob ']) >>> data = Randint (6, size= (8, 4)) >>> DataArray ([[2, 1, 2, 2] ,       [3, 3, 4, 2],       [0, 5, 3, 5],       [2, 1, 5, 2],       [1, 3, 0, 3],       [0, 0, 0, 1],       [0, 0, 0, 5],       [4, 2, 5 , 1]])

  

Suppose each name corresponds to a row in the data array, and we want to select all the rows that correspond to the name "Bob". We can do this.

>>> names = = ' Bob ' Array ([True, False,  true, False, False, False, False,  True], Dtype=bool) >>> Data[names = = ' Bob ']array ([[2, 1, 2, 2],       [0, 5, 3, 5],       [4, 2, 5, 1]])

  

The length of a Boolean array must be the same as the length of the array being indexed, and you can also mix a Boolean array with a Shard, integer (or integer sequence)

>>> Data[names = = ' Bob ', 2:]array ([[2, 2],       [3, 5],       [5, 1]]) >>> data[names = = ' Bob ', 3]array ([2, 5, 1]) >>> data[names = = ' Bob ', 3:]array ([[2],       [5],       [1]])

  

If you need to select multiple combinations of names to combine multiple Boolean conditions, you can use Boolean arithmetic operators such as & (and), | (OR):

>>> mask = (names = = ' Bob ') | (names = = ' would ') >>> Maskarray ([True, False,  True,  True,  true, False, False,  true], dtype= BOOL) >>> Data[mask]array ([[2, 1, 2, 2],       [0, 5, 3, 5],       [2, 1, 5, 2],       [1, 3, 0, 3],       [4, 2, 5, 1]] )

  

Note: The Python keyword and and or are not valid in Boolean data

Setting the value through a Boolean array is a frequently used means, in order to set all the even numbers in data to 3, we just need to:

>>> DataArray ([[2, 1, 2, 2],       [3, 3, 4, 2],       [0, 5, 3, 5],       [2, 1, 5, 2],       [1, 3, 0, 3],       [0, 0, 0 , 1],       [0, 0, 0, 5],       [4, 2, 5, 1]]) >>> data[data% 2 = 0] = 3>>> dataarray ([[3, 1, 3, 3],       [3 , 3, 3, 3],       [3, 5, 3, 5],       [3, 1, 5, 3],       [1, 3, 3, 3],       [3, 3, 3, 1],       [3, 3, 3, 5],       [3, 3, 5, 1] ])

  

Fancy Index

The fancy index is the numpy term, which refers to the use of an integer array for indexing. Suppose we have a 8x4 array:

>>> arr = Np.empty ((8, 4)) >>> for I in range (8): ...     Arr[i] = i...>>> arrarray ([[0.,  0.,  0.,  0.],       [1.,  1.,  1.,  1.],       [2.,  2.,  2.,  2.],       [3.,  3.,  3., 3.  ],       [4.,  4.,  4.,  4.],       [5.,  5.,  5.,  5.],       [6.,  6.,  6.,  6.],       [7.,  7.,  7.,  7.]] >>> arr[[3, 5, 0, 6]]array ([[3.,  3.,  3.,  3.],       [5.,  5.,  5.,  5.],       [ 0.,  0.,  0.,  0.],       [6.,  6.,  6.,  6.]) >>> arr[[3, -3, -1]]array ([[3.,  3.,  3.,  3.],       [5.,  5.,  5.,  5.],       [ 7.,  7.,  7.,  7.])

  

Arr[[3, 5, 0, 6]] will index the third row of the source array, row five, line 0th, line sixth, and then make a new view return, while Arr[[3,-3, 1]] will index the third row, the penultimate line, and the penultimate line

We generate a 8x4 array and pass in two indexed arrays [1, 5, 7, 2], [0, 3, 1, 2], and then we get a one-dimensional array

>>> arr = np.arange (+). Reshape ((8, 4)) >>> arrarray ([[0,  1,  2,  3],       [4,  5,  6,  7],       [8,  9, ten, one],       [[+], [+], [+], [+], [+], [+], [+], [+], [+], [+], [+], [+], []]       ) >>> Arr[[1, 5, 7, 2], [0, 3, 1, 2]]array ([4, 23, 29, 10])

  

Let's analyze what happens to the above code, the first indexed array [1, 5, 7, 2], we get the first row, the five rows, the seventh row, and the second row, and we will get the 0th column of the first row, the third column of row five, according to the second indexed array [0, 3, 1, 2]. And so on, finally, we get a one-dimensional array

Of course, in some cases, we want to get different rows of the source array in different order, and also to change the original column order after getting it, so we can do this:

>>> arr[[1, 5, 7, 2]]array ([[4,  5,  6,  7],       [[       ], [], [+], [8,  9 , ten, one]]) >>> arr[[1, 5, 7, 2]][:, [2, 1, 3, 0]]array ([[6,  5,  7,  4],       [       +],, [3] 0, +,  9, 8]  ) >>> arr[np.ix_ ([1, 5, 7, 2], [2, 1, 3, 0])]array ([[6],  5,
   7, 4], [[9], [+], [+], [+], [  8]])

  

As above, we can either use Arr[[1, 5, 7, 2]][:, [2, 1, 3, 0]] such a way to get different rows, and then change the order of the columns, but also with the NP.IX_ function to achieve the same purpose, but it should be noted that the fancy index is not the same as the Shard, It always copies the data into the new array:

>>> arr1 = Arr[np.ix_ ([1, 5, 7, 2], [2, 1, 3, 0])]>>> arr1array ([[6, 5,  7,  4],       [22, 21, [9], [+], [8]]  ) >>> arr1[1] = 66>>> Arr1array ([[6],  5,< C9/>7,  4],       [[       9,  8]] >>> arrarray ([[0], [+], [[]] ,  1,  2,  3],       [4,  5,  6,  7],       [8,  9, ten, one],       [       a], [       28,       29, 30, 31] [+], [+], [+], [+], [+]

  

 

  

  

  

Python str, list, NumPy shard operations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.