Numpy Array vs Python List: Advanced, Fancy, and Boolean Indexing

Advanced Indexing in Numpy

import numpy as np

# Creating a 2D numpy array
a = np.arange(24).reshape(6, 4)
print("Original array:")
print(a)

# Normal indexing
print("Element at row 1, column 2:", a[1, 2])

# Slicing
print("Sliced array (rows 1 to 2, columns 1 to 2):")
print(a[1:3, 1:3])

In this code, a 2D numpy array is created using arange and reshape. Advanced indexing is demonstrated with normal indexing to access a specific element and slicing to extract a subarray.

Fancy Indexing in Numpy

# Fancy indexing
print("Fancy indexing (all rows, columns 0, 2, and 3):")
print(a[:, [0, 2, 3]])

Fancy indexing is illustrated by selecting specific columns using an array of column indices. This allows for more flexible and customized indexing operations.

Boolean Indexing in Numpy

# Boolean indexing
rand_array = np.random.randint(1, 100, 24).reshape(6, 4)
print("Random 2D array:")
print(rand_array)

# Find all numbers greater than 50
print("Numbers greater than 50:")
print(rand_array[rand_array > 50])

# Find even numbers
print("Even numbers:")
print(rand_array[rand_array % 2 == 0])

# Find numbers greater than 50 and are even
print("Numbers greater than 50 and even:")
print(rand_array[(rand_array > 50) & (rand_array % 2 == 0)])

# Find numbers not divisible by 7
print("Numbers not divisible by 7:")
print(rand_array[~(rand_array % 7 == 0)])

Boolean indexing is showcased using a random 2D numpy array. Filtering operations are performed to find numbers greater than 50, even numbers, numbers greater than 50 and even, and numbers not divisible by 7.

Broadcasting in Numpy

Broadcasting Rules

1. Make the two arrays have the same number of dimensions.

  • If the numbers of dimensions of the two arrays are different, add new dimensions with size 1 to the head of the array with the smaller dimension.

2. Make each dimension of the two arrays the same size.

  • If the sizes of each dimension of the two arrays do not match, dimensions with size 1 are stretched to the size of the other array.
  • If there is a dimension whose size is not 1 in either of the two arrays, it cannot be broadcasted, and an error is raised.

# Broadcasting example with same shape arrays
a = np.arange(6).reshape(2, 3)
b = np.arange(6, 12).reshape(2, 3)

print("Array a:")
print(a)

print("Array b:")
print(b)

print("Result of broadcasting:")
print(a + b)

This code demonstrates broadcasting in numpy with arrays of the same shape. The + operation is applied element-wise without the need for explicit looping.

# Broadcasting example with different shape arrays
a = np.arange(6).reshape(2, 3)
b = np.arange(3).reshape(1, 3)

print("Array a:")
print(a)

print("Array b:")
print(b)

print("Result of broadcasting:")
print(a + b)

Here, broadcasting is showcased with arrays of different shapes. The smaller array is broadcasted to the shape of the larger array, making the operation possible.

Working with Mathematical Formulas in Numpy

# Applying mathematical formulas using numpy
a = np.arange(10)

# Calculate sine of each element
print("Sine of array a:")
print(np.sin(a))

This section demonstrates the application of mathematical formulas using numpy. In this case, the sine function is applied element-wise to an array.

Sigmoid Function and Mean Squared Error in Numpy

Sigmoid Function in Numpy

# Sigmoid function in numpy
def sigmoid(array):
    return 1 / (1 + np.exp(-array))

a = np.arange(100)
print("Sigmoid of array a:")
print(sigmoid(a))

The sigmoid function is implemented in numpy. It is commonly used in machine learning for binary classification tasks.

Mean Squared Error in Numpy

# Mean Squared Error in numpy
actual = np.random.randint(1, 50, 25)
predicted = np.random.randint(1, 50, 25)

def mse(actual, predicted):
    return np.mean((actual - predicted)**2)

print("Mean Squared Error:")
print(mse(actual, predicted))

The mean squared error is calculated using numpy, providing a measure of the average squared difference between the actual and predicted values.

Working with Missing Values in Numpy

# Working with missing values in numpy (np.nan)
array_with_nan = np.array([1, 2, 3, 4, np.nan, 6])
print("Array with NaN values:")
print(array_with_nan)

# Remove NaN values
print("Array without NaN values:")
print(array_with_nan[~np.isnan(array_with_nan)])

Numpy’s handling of missing values (represented by np.nan) is demonstrated. The code removes NaN values from the array.

Plotting Graphs in Numpy

# Plotting 2D graphs using numpy and matplotlib
import matplotlib.pyplot as plt

# Example 1: Linear plot
x = np.linspace(-10, 10, 100)
y = x
plt.plot(x, y)
plt.title("Linear Plot")
plt.show()

# Example 2: Quadratic plot
x = np.linspace(-10, 10, 100)
y = x**2
plt.plot(x, y)
plt.title("Quadratic Plot")
plt.show()

# Example 3: Sine plot
x = np.linspace(-10, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Plot")
plt.show()

Various 2D plots are generated using numpy and matplotlib. Examples include linear, quadratic, and sine plots, showcasing the versatility of numpy for creating data for visualization.

111 Replies to “Advanced Numpy”

  1. Профессиональные seo https://seo-optimizaciya-kazan.ru услуги для максимизации онлайн-видимости вашего бизнеса. Наши эксперты проведут глубокий анализ сайта, оптимизируют контент и структуру, улучшат технические аспекты и разработают индивидуальные стратегии продвижения.

  2. Реальные анкеты проституток https://prostitutki-213.ru Москвы с проверенными фото – от элитных путан до дешевых шлюх. Каталог всех индивидуалок на каждой станции метро с реальными фотографиями без ретуши и с отзывами реальных клиентов.

  3. Thibaut Nicolas Marc Courtois https://thibaut-courtois.real-madrid-ar.com Footballeur belge, gardien de but du Club espagnol “Real Madrid”. Lors de la saison 2010/11, il a ete reconnu comme le meilleur gardien de la Pro League belge, ainsi que comme joueur de l’annee pour Genk. Trois fois vainqueur du Trophee Ricardo Zamora, decerne chaque annee au meilleur gardien espagnol

  4. Совсем недавно открылся новый интернет портал BlackSprut (Блекспрут) https://bs2cite.cc в даркнете, который предлагает купить нелегальные товары и заказать запрещенные услуги. Самая крупнейшая площадка СНГ. Любимые шопы и отзывчивая поддержка.

  5. Game World https://kz-games.kz offers the latest online gaming news, game reviews, gameplay and ideas, gaming tactics and tips . Start playing our most popular and amazing games and get ready to become the leader in the online gaming world!

  6. Сайт https://ps-likers.ru предлагает уроки по фотошоп для начинающих. На страницах сайта можно найти пошаговые руководства по анимации, созданию графики для сайтов, дизайну, работе с текстом и фотографиями, а также различные эффекты.

Leave a Reply

Your email address will not be published. Required fields are marked *