#2891

Method Chaining

Easy
DataFrame operationsMethod chainingFiltering and sorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Using method chaining in Pandas allows us to perform filtering and sorting in a single line of code. This is efficient and leverages the power of Pandas to handle data operations seamlessly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use the DataFrame's filter method to select rows where weight > 100.
  2. 2Step 2: Use the sort_values method to sort the filtered DataFrame by weight in descending order.
  3. 3Step 3: Use the loc method to select only the 'name' column from the sorted DataFrame.
solution.py11 lines
1import pandas as pd
2
3animals = pd.DataFrame({
4    'name': ['Tatiana', 'Khaled', 'Alex', 'Jonathan', 'Stefan', 'Tommy'],
5    'species': ['Snake', 'Giraffe', 'Leopard', 'Monkey', 'Bear', 'Panda'],
6    'age': [98, 50, 6, 45, 100, 26],
7    'weight': [464, 41, 328, 463, 50, 349]
8})
9
10result = animals[animals['weight'] > 100].sort_values(by='weight', ascending=False)['name'].tolist()
11print(result)

Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) because we create a new list to store the results.

  • 1Method chaining simplifies code and improves readability.
  • 2Filtering and sorting can be done efficiently in one line.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.