<jupyter_start><jupyter_text>**How to index and slice NumPy arrays****Extensions to the Python indexing syntax that are available with NumPy****Differences between indexing and slicing in NumPy and in Python**<jupyter_code>import numpy as np
#Indexing for 1D arrays

v = np.linspace(0,10,5)

v
v[1]
v[-1]
v[5]    #non-existent item
#Indexing for 2D arrays

vv = np.random.random((5,4))
vv
vv[0,0]
vv[4,3]<jupyter_output><empty_output><jupyter_text>This is different than we would do with Python lists. The closest analog to a two dimensional array that we could build with lists would be a list of lists such as<jupyter_code>ll = [[1,2,3],[4,5,6],[7,8,9]]
ll[1,2]
ll[1][2]
#Slicing of 1D array

v[2:4]
#Slicing of 2D array

vv[2]
vv[2:5,1]
vv[2:5,1:2]
vv[2:-1,:]
vv[:,::2]<jupyter_output><empty_output><jupyter_text>One important difference though is that NumPy slices yield views onto the same piece of memory, so if we create a new array by slicing and modify its values, we end up modifying the original array.<jupyter_code>v2 =v[2:4]  #v2 is a small slice of 1D array
v2[0] = 0   #element 0 changed to 0
v    #that value has been changed in the original array as well
# if we need a copy, we need to explicitly make it in Numpy

v3 = v[2:4].copy()
v3[0] = 1
v
# ADVANCED INDEXING

# 1. We can use a list of indices or a numpy array of indices to select only certain elements

v[[1,2,3]]<jupyter_output><empty_output><jupyter_text>The other extension consists of using an array of Boolean values, true or false, to choose which elements to include and which not to. The easiest way to build such an array is with a comparison operator or in a quality operator.<jupyter_code>v>0
bool_index = v > 0
v[bool_index]
#  This kind of indexing is often used to modify only carefully selected parts of an array.

vv
vv[vv > 0.5] = vv[vv > 0.5]*2
vv<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09882478632478632, 'fraction_numerical': 0.03739316239316239, 'mean_word_length': 4.908517350157728, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '633859', 'license': 'MIT', 'n_tokens_mistral': 681, 'n_tokens_neox': 657, 'n_words': 268, 'path': '06 indexing.ipynb', 'repo_name': 'AryaDevops/Python-for-DataScience', 'size': '1872'}