This post was released as part of the Data Science Blogathon.
Introduction
An iteration is an object that repeats identical or similar tasks without making mistakes. In a way, we can say that repeated execution of a set of statements is what iteration is all about. Piton has several language features to help perform the iteration task.
As object, the iterator counts a series of values that can be iterated over. The lists, tuples, dictionaries, strings and sets are all iterable objects. Son iterables containers from which you can get an iterator.
In the next topic, we will see a summary of the different iteration processes.
Loop using enumerate ()
Using a for loop to iterate over a list only gives us access to all the items in the list in each execution, one after another. Si uno además quiere entrar a la data del indexThe "Index" It is a fundamental tool in books and documents, which allows you to quickly locate the desired information. Generally, it is presented at the beginning of a work and organizes the contents in a hierarchical manner, including chapters and sections. Its correct preparation facilitates navigation and improves the understanding of the material, making it an essential resource for both students and professionals in various areas...., then, where is the element of the list that we are iterating over, we can use enumerate().
As an example, watch how by The loop was converted by creating a list of areas:
# areas list
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Change for loop to use enumerate() and updateThe term "UPDATE" It is commonly used in the technological and communication field to refer to the action of updating information, Software or Systems. In a world in constant evolution, Updates are essential to improve security, fix bugs and add new features. Businesses and users should keep an eye on available updates to ensure optimal performance and maintain the integrity of their devices and data.... print()
for x, y in enumerate(areas) :
print("room ", str(x), ": ", str(Y))
Production:
room 0: 11.20 room 1: 18.0 room 2: 20.0 room 3: 10.75 room 4: 9.5
Loop over dictionary – items ()
In Python 3, we need the items() method to loop over a dictionary. On each iteration, "the capital of x is y" will be printed out, where x is the key and y is the value of the pair.
# Definition of dictionary europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'austria':'vienna' } # Iterate over europe for x, y in europe.items(): print("the capital of ", str(x), " is ", str(Y))
Production:
the capital of norway is oslo
the capital of poland is warsaw
the capital of italy is rome
the capital of spain is madrid
the capital of austria is vienna
the capital of germany is berlin
Bucle sobre matriz Numpy – e.g. enditer ()
Si estamos tratando con una matriz 1D Numpy, recorrer todos los ítems puede ser tan simple como:
for x in my_array :
Si estamos tratando con una matriz 2D Numpy, is more complex. Una matriz 2D está formada por varias matrices 1D. Para iterar explícitamente sobre todos los ítems separados de una matriz multidimensional, necesitaremos esta sintaxis:
for x in np.nditer(my_array) :
Then, escribimos un bucle for que itera sobre todos los ítems de np_height e imprime “x pulgadas” para cada elemento, donde x es el valor de la matriz.
# Import numpy as np import numpy as np # For loop over np_height for x in np_height: print(x, "inches") # For loop over np_baseball for n in np.nditer(np_baseball): print(n)
Production:
74 inches 74 inches 72 inches 72 inches 73 inches 69 inches 69 inches 71 inches 76 inches 71 inches 73 inches…..
Recorriendo iterrows ():
Usando iterrows () para iterar sobre cada observación de un Pandas DataFrame. Here, estamos usando un bucle for para agregar una nueva columna, llamada PAÍS, que contiene una versión en mayúsculas de los nombres de los países en la columna “country”. Estamos usando el método de cadena superior() for this.
# Import cars data import pandas as pd cars = pd.read_csv('cars.csv', index_col = 0) # Code for loop that adds COUNTRY column for lab, row in cars.iterrows(): cars.loc[lab, "COUNTRY"] = row['country'].upper() # Print cars print(cars)
Utilizar iterrows () para iterar sobre cada observación de un Pandas DataFrame es fácil de comprender, pero no muy eficiente. In each iteration, estamos creando una nueva serie Pandas en Python. Si queremos agregar una columna a un DataFrame llamando a una función en otra columna, el método iterrows () en combinación con un bucle for no es la forma preferida de hacerlo. Instead, queremos utilizar request()
A continuación usaremos el request() versión para obtener el mismo resultado en el DataFrame:
# Use .apply(str.upper) cars["COUNTRY"] = cars["country"].apply(str.upper) print(cars)
Production:
cars_per_cap country drives_right (US, COUNTRY) US 809 United States True UNITED STATES AUS 731 Australia False AUSTRALIA JPN 588 Japan False JAPAN IN 18 India False INDIA RU 200 Russia True RUSSIA MOR 70 Morocco True MOR
Podemos usar las herramientas de iteración anteriores para trabajar con la iteración en Python de una manera más efectiva. Este fue solo el resumen de la iteración. Se puede trabajar con diferentes ejemplos.
The media shown in this post is not the property of DataPeaker and is used at the author's discretion.