Translate

Saturday 6 April 2024

Indexing and slicing for 1D NumPy arrays with illustrative examples.

 Indexing and slicing for 1D NumPy arrays with illustrative examples.

Fundamentals

  • 1D Arrays: Think of 1D arrays as simple lists of numbers.

  • Zero-Based Indexing: The first element has an index of 0, the second has an index of 1, and so on.

Example Array


Python


import numpy as np

arr = np.array([10, 5, -3, 8, 2])
print(arr)  # Output: [10  5 -3  8  2]

Indexing (Accessing Elements)

  • Syntax: array_name[index]

  • Examples:

  • first_element = arr[0] (Accesses the value 10)

  • third_element = arr[2] (Accesses the value -3)

Slicing

  • Syntax: array_name[start:end:step]

  • start: Starting index (inclusive)

  • end: Ending index (exclusive)

  • step: Step size between included elements

  • Examples:

  • sub_arr = arr[1:4] # Elements from index 1 to 3 (Output: [5 -3 8])

  • every_other = arr[::2] # Every other element (Output: [10 -3 2])

  • reversed_arr = arr[::-1] # Reverse the array (Output: [ 2 8 -3 5 10])

Additional Examples

  • Last Element
    Python
    last_element = arr[-1]

  • Last Three Elements:
    Python
    last_three = arr[-3:]

Key Notes

  • Negative Indexing: Using negative indices starts counting from the end of the array.

  • Modifying Through Slices: Changes you make to a slice of a NumPy array are reflected in the original array.

Important: Slices and Copies

If you need an independent copy of a portion of the array, use the .copy() method explicitly.


Python


modified_slice = arr[1:3].copy()  # Creates a separate copy
modified_slice[0] = 100               # Doesn't change the original 'arr'


—----------------------


how to extract the first three elements from a NumPy array:

Using Slicing:


Python


import numpy as np

arr = np.array([10, 5, -3, 8, 2])

first_three = arr[:3# Slice from the beginning (index 0) up to index 3 (exclusive)
print(first_three)  # Output: [10  5 -3]

Explanation:

  • : before index 3: Implies taking elements from the start of the array.

  • Index 3 is not included: Slicing in Python goes up to but does not include the ending index.




 how you would select the middle element of a NumPy array if it has an odd number of elements:


Python


import numpy as np

def get_middle_element(arr):
    if len(arr) % 2 == 0# Check if the array length is even
        print("Array has an even number of elements, no single middle element.")
        return None 

    middle_index = len(arr) // 2  # Integer division to find the middle index
    middle_element = arr[middle_index]
    return middle_element

# Example with an odd-length array
odd_array = np.array([5, 2, 9, -1, 4])

middle = get_middle_element(odd_array)
print(middle)  # Output: 9

Explanation

  1. Function for Flexibility: The code is encapsulated in a function get_middle_element() for reusability.

  2. Even Check: First, we check if the array length is even. If so, it has no single, well-defined middle element.

  3. Middle Index: If the array is odd-length, we use integer division (//) to find the middle index directly.

  4. Element Access: The middle element is accessed using its index.

Let's Test It!


Python


even_array = np.array([1, 3, 6, 2])
get_middle_element(even_array)  # Output: "Array has an even number of elements..."

how to replace the first two elements of a NumPy array with zeros:

Using Slicing and Assignment


Python


import numpy as np

arr = np.array([10, 5, -3, 8, 2])

arr[:2] = 0  # Assign zero to the slice containing the first two elements
print(arr)  # Output: [0 0 -3  8  2]

Explanation

  1. Slicing: arr[:2] selects the first two elements of the array.

  2. Assignment: We assign the value 0 to the selected slice. NumPy efficiently broadcasts this zero value to replace both elements within the slice.

Key Point: Modifying Slices

In NumPy, slices often act as views into the original array. This means changing a slice also modifies the corresponding elements in the original array.

Let's Experiment!

Here are a few variations to try:

  • Replace last three elements with 1
    Python
    arr[-3:] = 1

  • Replace every other element starting from the first one with -1
    Python
    arr[::2] = -1

Let me know if you have any specific replacement patterns in mind, and I'll gladly help you implement them in NumPy!



A sum of money at simple interest amounts to Rs. 815 in 3 years and to Rs. 854 in 4 years. What is the original sum of money (the principal)?

 Problem:

A sum of money at simple interest amounts to Rs. 815 in 3 years and to Rs. 854 in 4 years. What is the original sum of money (the principal)?


  • A) Rs. 650

  • B) Rs. 690

  • C) Rs. 698

  • D) Rs. 700

Explanation:

  1. Find the Simple Interest (SI) earned in one year: The difference in the amounts after 4 years and 3 years represents the simple interest earned in one year. SI = Rs. 854 - Rs. 815 = Rs. 39

  2. Find the SI earned in three years: Since the interest is simple, it will be the same amount earned each year. SI for 3 years = Rs. 39 * 3 = Rs. 117

  3. Calculate the principal: The principal is the original sum of money. To find it, subtract the total simple interest earned from the amount after 3 years. Principal = Rs. 815 - Rs. 117 = Rs. 698

Answer:

The correct answer is C) Rs. 698



Hindi

 संकट:

साधारण ब्याज पर एक धनराशि रु. 3 साल में 815 रु. 4 साल में 854 रु. मूल धनराशि (मूलधन) क्या है?


  • ए) रु. 650

  • बी) रु. 690

  • सी) रु. 698

  • डी) रु. 700

स्पष्टीकरण:

  1. एक वर्ष में अर्जित साधारण ब्याज (SI) ज्ञात करें: 4 वर्ष और 3 वर्ष के बाद की राशि में अंतर एक वर्ष में अर्जित साधारण ब्याज को दर्शाता है। एसआई = रु. 854 - रु. 815 = रु. 39

  2. तीन वर्षों में अर्जित एसआई ज्ञात करें: चूंकि ब्याज सरल है, यह प्रत्येक वर्ष अर्जित समान राशि होगी। 3 वर्ष के लिए एसआई = रु. 39 * 3 = रु. 117

  3. मूलधन की गणना करें: मूलधन मूल राशि है। इसे ज्ञात करने के लिए, 3 वर्षों के बाद अर्जित कुल साधारण ब्याज को राशि से घटा दें। मूलधन = रु. 815 - रु. 117 = रु. 698

उत्तर:

सही उत्तर है C) रु. 698



Telugu

 సమస్య:

సాధారణ వడ్డీకి మొత్తం రూ. 3 సంవత్సరాలలో 815 మరియు రూ. 4 సంవత్సరాలలో 854. అసలు డబ్బు (ప్రిన్సిపాల్) ఎంత?


  • ఎ) రూ. 650

  • బి) రూ. 690

  • సి) రూ. 698

  • డి) రూ. 700

వివరణ:

  1. ఒక సంవత్సరంలో సంపాదించిన సాధారణ వడ్డీ (SI)ని కనుగొనండి: 4 సంవత్సరాలు మరియు 3 సంవత్సరాల తర్వాత మొత్తాలలో వ్యత్యాసం ఒక సంవత్సరంలో సంపాదించిన సాధారణ వడ్డీని సూచిస్తుంది. SI = రూ. 854 - రూ. 815 = రూ. 39

  2. మూడు సంవత్సరాలలో సంపాదించిన SIని కనుగొనండి: వడ్డీ చాలా సులభం కనుక, ప్రతి సంవత్సరం సంపాదించిన అదే మొత్తం ఉంటుంది. 3 సంవత్సరాలకు SI = రూ. 39 * 3 = రూ. 117

  3. ప్రిన్సిపల్‌ను లెక్కించండి: ప్రిన్సిపాల్ అనేది అసలు మొత్తం డబ్బు. దాన్ని కనుగొనడానికి, 3 సంవత్సరాల తర్వాత సంపాదించిన మొత్తం నుండి సాధారణ వడ్డీని తీసివేయండి. ప్రిన్సిపాల్ = రూ. 815 - రూ. 117 = రూ. 698

సమాధానం:

సరైన సమాధానం సి) రూ. 698



Tamil

 பிரச்சனை:

எளிய வட்டியில் ஒரு தொகை ரூ. 3 ஆண்டுகளில் 815 மற்றும் ரூ. 4 ஆண்டுகளில் 854. பணத்தின் அசல் தொகை என்ன (முதன்மை)?


  • A) ரூ. 650

  • B) ரூ. 690

  • C) ரூ. 698

  • D) ரூ. 700

விளக்கம்:

  1. ஒரு வருடத்தில் சம்பாதித்த எளிய வட்டியைக் (SI) கண்டறிக: 4 ஆண்டுகள் மற்றும் 3 ஆண்டுகளுக்குப் பிறகு தொகைகளில் உள்ள வேறுபாடு, ஒரு வருடத்தில் சம்பாதித்த எளிய வட்டியைக் குறிக்கிறது. எஸ்ஐ = ரூ. 854 - ரூ. 815 = ரூ. 39

  2. மூன்று ஆண்டுகளில் பெற்ற எஸ்ஐயைக் கண்டறியவும்: வட்டி எளிமையாக இருப்பதால், ஒவ்வொரு ஆண்டும் சம்பாதித்த அதே தொகையாக இருக்கும். 3 ஆண்டுகளுக்கு எஸ்ஐ = ரூ. 39 * 3 = ரூ. 117

  3. முதன்மையைக் கணக்கிடுங்கள்: முதன்மையானது பணத்தின் அசல் தொகையாகும். அதைக் கண்டுபிடிக்க, 3 ஆண்டுகளுக்குப் பிறகு சம்பாதித்த மொத்த எளிய வட்டியைக் கழிக்கவும். முதன்மை = ரூ. 815 - ரூ. 117 = ரூ. 698

பதில்:

சரியான பதில் C) ரூ. 698



Spanish


 Problema:

Una suma de dinero a interés simple asciende a Rs. 815 en 3 años y a Rs. 854 en 4 años. ¿Cuál es la suma de dinero original (el principal)?


  • A) Rs. 650

  • B) rupias. 690

  • C) Rs. 698

  • D) rupias. 700

Explicación:

  1. Encuentre el interés simple (SI) ganado en un año: la diferencia en las cantidades después de 4 años y 3 años representa el interés simple ganado en un año. SI = Rs. 854 - rupias. 815 = rupias. 39

  2. Encuentre el SI ganado en tres años: Como el interés es simple, será la misma cantidad ganada cada año. SI durante 3 años = Rs. 39 * 3 = rupias. 117

  3. Calcule el principal: El principal es la suma de dinero original. Para encontrarlo, resta el interés simple total ganado del monto después de 3 años. Principal = Rs. 815 - rupias. 117 = rupias. 698

Respuesta:

La respuesta correcta es C) Rs. 698



French

 Problème:

Une somme d’argent à intérêts simples s’élève à Rs. 815 en 3 ans et à Rs. 854 en 4 ans. Quelle est la somme d’argent initiale (le principal) ?


  • A) Rs. 650

  • B) Rs. 690

  • C) Rs. 698

  • D) Rs. 700

Explication:

  1. Trouvez les intérêts simples (SI) gagnés en un an : La différence entre les montants après 4 ans et 3 ans représente les intérêts simples gagnés en un an. SI = Rs. 854 - Rs. 815 = Rs. 39

  2. Trouvez le SI gagné en trois ans : Comme les intérêts sont simples, ce sera le même montant gagné chaque année. SI pour 3 ans = Rs. 39 * 3 = Rs. 117

  3. Calculez le principal : Le principal est la somme d’argent initiale. Pour le trouver, soustrayez le total des intérêts simples gagnés du montant après 3 ans. Principal = Rs. 815 - Rs. 117 = Rs. 698

Répondre:

La bonne réponse est C) Rs. 698