About Lesson
Sorting and filtering are important tasks when analyzing data.
1. Sorting Data
You can sort data by a specific column using sort_values()
:
df_sorted = df.sort_values(by='Age', ascending=False) # Sort by Age in descending order
print(df_sorted)
2. Filtering Rows Based on Conditions
You can filter rows based on conditions using boolean indexing:
filtered_df = df[df['Age'] > 30] # Select rows where Age > 30
print(filtered_df)
For multiple conditions, combine them with &
(AND) or |
(OR):
filtered_df = df[(df['Age'] > 25) & (df['City'] == 'New York')]
print(filtered_df)