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,
1234567# 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.
1234567# 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)])
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Ställ mig frågor om detta ämne
Sammanfatta detta kapitel
Visa verkliga exempel
Awesome!
Completion rate improved to 3.33
Accessing using .loc[] [3/3]
Svep för att visa menyn
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,
1234567# 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.
1234567# 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)])
Tack för dina kommentarer!