python/slicing_1D_arrays.py

31 lines
1.1 KiB
Python

import numpy as np
array = np.array([5, 10, 2, 8, 9, 1, 0, 4])
print(f'Initial array: {array}')
# Slicing from the element at index 2 to the element at index 4 exclusive
print(array[2:4])
# Slicing from the first element to the element at index 5 exclusive
print(array[:5])
# Slicing from the element at index 5 to the last element inclusive
print(array[5:])
#import numpy as np
# Initial array
array = np.array([5, 10, 2, 8, 9, 1, 0, 4])
print(f'Initial array: {array}')
# Slicing from the first element to the last element inclusive with step=2
print(array[::2])
# Slicing from the element at index 4 to the element at index 2 exclusive (step=-1)
print(array[4:2:-1])
# Slicing from the last element to the first element inclusive (reversed array)
print(array[::-1])
# Slicing from the first element to the last inclusive (the same as our array)
print(array[:])
# Sales data for the past week (Monday to Sunday)
weekly_sales = np.array([150, 200, 170, 180, 160, 210, 190])
# Create a slice of weekly_sales with every second day's sales starting from the second day
alternate_day_sales = weekly_sales[1::2]
print(alternate_day_sales)