Contenido del Curso
Introduction to pandas [track]
Introduction to pandas [track]
Accessing using .loc[] [3/3]
Two chapters ago it was mentioned that boolean array can be used to access rows with the .loc[]
property. It means you can filter rows without using if/else
statements!
A condition you want to use for filtering must be passed as the first parameter. For example,
# Importing library import pandas as pd # Reading csv file df = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/67798cef-5e7c-4fbc-af7d-ae96b4443c0a/audi.csv') # Get the cars manufactured before 2000 print(df.loc[df.year < 2000])
If you want to filter based on several conditions, you need to put them within separate parentheses, and combine them by either the &
(and
), or |
(or
) operator. You use the &
operator if you need all the conditions to be hold. If you are interested in at least one of the conditions, use the |
operator.
# Importing library import pandas as pd # Reading csv file df = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/67798cef-5e7c-4fbc-af7d-ae96b4443c0a/audi.csv') # Get the Diesel cars cheaper than 15k print(df.loc[(df.fuelType == 'Diesel') & (df.price < 15000)])
¡Gracias por tus comentarios!