Given a Matrix, the task is to write a Python program to remove rows that have certain positions.
Example:
Input: test_list = [[3, 5, 2], [1, 8, 9],
[5, 3, 1], [0, 1, 6],
[9, 4, 1], [1, 2, 10],
[0, 1, 2]]; idx_lis = [1, 2, 5]
Output: [[3, 5, 2], [0, 1, 6], [9, 4, 1], [0, 1, 2]]
Explanation: 1st, 2nd and 5th rows are removed.
Input: test_list = [[3, 5, 2], [1, 8, 9],
[5, 3, 1], [0, 1, 6],
[9, 4, 1], [1, 2, 10],
[0, 1, 2]]; idx_lis = [1, 3, 5]
Output: [[3, 5, 2], [5, 3, 1], [9, 4, 1], [0, 1, 2]]
Explanation: 1st, 3rd and 5th rows are removed.
Method #1 : Using loop + pop() + back iteration
In this, removal is handled using pop(), and back iteration is necessary to make sure due to rearrangement at deletion, the wrong positional row is not removed.
Python3
# Python3 code to demonstrate working of
# Remove positional rows
# Using loop + pop() + back iteration
# initializing list
test_list = [[3, 5, 2], [1, 8, 9], [5, 3, 1],
[0, 1, 6], [9, 4, 1], [1, 2, 10],
[0, 1, 2]]
# printing original list
print("The original list is: " + str(test_list))
# initializing indices
idx_lis = [1, 2, 5]
# back iteration
for idx in idx_lis[::-1]:
# pop() used for removal
test_list.pop(idx)
# printing result
print("Matrix after removal: " + str(test_list))
Output:
The original list is: [[3, 5, 2], [1, 8, 9], [5, 3, 1], [0, 1, 6], [9, 4, 1], [1, 2, 10], [0, 1, 2]]
Matrix after removal: [[3, 5, 2], [0, 1, 6], [9, 4, 1], [0, 1, 2]]
Time Complexity: O(n*m)
Auxiliary Space: O(k)
Method #2 : Using enumerate() + list comprehension
In this, rather than removing rows by index, we perform the task of only adding rows that are not part of removing the index list.
Python3
# Python3 code to demonstrate working of
# Remove positional rows
# Using enumerate() + list comprehension
# initializing list
test_list = [[3, 5, 2], [1, 8, 9], [5, 3, 1],
[0, 1, 6], [9, 4, 1], [1, 2, 10],
[0, 1, 2]]
# printing original list
print("The original list is: " + str(test_list))
# initializing indices
idx_lis = [1, 2, 5]
# using enumerate() to get index and value of each row
res = [sub[1] for sub in enumerate(test_list) if sub[0] not in idx_lis]
# printing result
print("Matrix after removal: " + str(res))
Output:
The original list is: [[3, 5, 2], [1, 8, 9], [5, 3, 1], [0, 1, 6], [9, 4, 1], [1, 2, 10], [0, 1, 2]]
Matrix after removal: [[3, 5, 2], [0, 1, 6], [9, 4, 1], [0, 1, 2]]
Time Complexity: O(m*n) as the number of combinations generated is M choose N.
Auxiliary Space: O(m*n) as the size of the resultant list is also M choose N.
Method 3: Using the filter() function with lambda function to remove rows based on the given indices.
 Step-by-step approach:
- Define the list of lists.
- Define the list of indices to be removed.
- Use the filter() function along with the lambda function to remove the rows from the list based on the given indices.
- Convert the filtered object into a list.
- Print the resulting list.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Remove positional rows
# Using filter() function with lambda function
# initializing list
test_list = [[3, 5, 2], [1, 8, 9], [5, 3, 1],
[0, 1, 6], [9, 4, 1], [1, 2, 10],
[0, 1, 2]]
# printing original list
print("The original list is: " + str(test_list))
# initializing indices
idx_lis = [1, 2, 5]
# using filter() function with lambda function to remove rows based on given indices
res = list(filter(lambda x: test_list.index(x) not in idx_lis, test_list))
# printing result
print("Matrix after removal: " + str(res))
OutputThe original list is: [[3, 5, 2], [1, 8, 9], [5, 3, 1], [0, 1, 6], [9, 4, 1], [1, 2, 10], [0, 1, 2]]
Matrix after removal: [[3, 5, 2], [0, 1, 6], [9, 4, 1], [0, 1, 2]]
Time complexity: O(n) where n is the number of rows in the list of lists.
Auxiliary space: O(1) as we are not using any extra space to store the intermediate results.
Method 4: Using numpy.delete() function
Another alternative approach to remove positional rows from a list is by using the numpy.delete() function. The numpy.delete() function is a built-in function of the numpy library that can delete the specified subarrays along the given axis from the input array.
Here's the step-by-step approach:
- Import the numpy library.
- Initialize the list as a numpy array.
- Use the numpy.delete() function to remove the subarrays with the given indices to remove along the first axis (axis=0).
- Convert the resulting numpy array back to a list.
- Print the result.
Python3
# Python3 code to demonstrate working of
# Remove positional rows
# Using numpy.delete() function
# import numpy library
import numpy as np
# initializing list
test_list = [[3, 5, 2], [1, 8, 9], [5, 3, 1],
[0, 1, 6], [9, 4, 1], [1, 2, 10],
[0, 1, 2]]
# printing original list
print("The original list is: " + str(test_list))
# initializing indices
idx_lis = [1, 2, 5]
# converting list to numpy array
test_arr = np.array(test_list)
# using numpy.delete() function to remove subarrays with given indices
test_arr = np.delete(test_arr, idx_lis, axis=0)
# converting numpy array back to list
test_list = test_arr.tolist()
# printing result
print("Matrix after removal: " + str(test_list))
OUTPUT:
The original list is: [[3, 5, 2], [1, 8, 9], [5, 3, 1], [0, 1, 6], [9, 4, 1], [1, 2, 10], [0, 1, 2]]
Matrix after removal: [[3, 5, 2], [0, 1, 6], [9, 4, 1], [0, 1, 2]]
Time complexity: O(n), where n is the length of the original list.
Auxiliary space: O(n), since a new numpy array is created and then converted back to a list
Method #5: Using a boolean mask with a numpy array
- The program imports the numpy library and assigns it to the alias "np".
- A 2-dimensional list "test_list" is defined as containing 7 sublists, each containing 3 integer elements.
- Another list "idx_lis" is defined as containing 3 integer elements.
- The numpy array is created by passing the "test_list" to the np.array() function.
- A boolean mask is created using the np.ones() function to create an array of all True values, with the same length as "test_list". Then the elements of the "idx_lis" are set to False in the mask array to mark the rows to be removed.
- The boolean mask is then used to select the rows to keep from the numpy array by using the mask as an index. This is done by passing the mask array as the index to the numpy array "arr", resulting in a reduced array "res".
- The resulting array "res" is converted back to a list by using the tolist() method of the numpy array object.
- Finally, the result list "res_list" is printed to the console as a string.
Below is the implementation of the above approach:
Python3
# Python program for the above approach
import numpy as np
test_list = [[3, 5, 2], [1, 8, 9], [5, 3, 1],
[0, 1, 6], [9, 4, 1], [1, 2, 10],
[0, 1, 2]]
idx_lis = [1, 2, 5]
# Convert the list to numpy array
arr = np.array(test_list)
# Create a boolean mask for rows to be kept
mask = np.ones(len(test_list), dtype=bool)
mask[idx_lis] = False
# Use the boolean mask to select rows to keep
res = arr[mask]
# Convert the result back to list
res_list = res.tolist()
# Print the result
print("Matrix after removal: " + str(res_list))
Output:
Matrix after removal: [[3, 5, 2], [0, 1, 6], [9, 4, 1], [0, 1, 2]]
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Python Remove Dictionary Item
Sometimes, we may need to remove a specific item from a dictionary to update its structure. For example, consider the dictionary d = {'x': 100, 'y': 200, 'z': 300}. If we want to remove the item associated with the key 'y', several methods can help achieve this. Letâs explore these methods.Using pop
2 min read
Python Remove Set Items
Python sets are an efficient way to store unique, unordered items. While adding items to a set is straightforward, removing items also offers a variety of methods. This article will guide you through the different techniques available to remove items from a set in Python.Remove single set item using
3 min read
Python - Remove Top level from Dictionary
Sometimes, while working with Python Dictionaries, we can have nesting of dictionaries, with each key being single values dictionary. In this we need to remove the top level of dictionary. This can have application in data preprocessing. Lets discuss certain ways in which this task can be performed.
3 min read
Python - Remove rows with Numbers
Given a Matrix, remove rows with integer instances. Input : test_list = [[4, 'Gfg', 'best'], ['gfg', 5, 'is', 'best'], [3, 5], ['GFG', 'Best']] Output : [['GFG', 'Best']] Explanation : All rows with numbers are removed. Input : test_list = [[4, 'Gfg', 'best'], ['gfg', 5, 'is', 'best'], [3, 5], ['GFG
7 min read
Python | Remove False row from matrix
Sometimes, while handling data, especially in the Machine Learning domain, we need to go through a lot of incomplete or empty data. We sometimes need to eliminate the rows which do not contain a value in any of the columns. Let's discuss certain ways to remove the rows that have all False values as
9 min read
Python - Remove List Item
Removing List Item can be achieved using several built-in methods that provide flexibility in how you remove list items. In this article, we'll explore the different ways to remove list items in Python.Removing Item by Value with remove()The remove() method allows us to remove the first occurrence o
3 min read
Python - Remove Item from Dictionary
There are situations where we might want to remove a specific key-value pair from a dictionary. For example, consider the dictionary d = {'x': 10, 'y': 20, 'z': 30}. If we need to remove the key 'y', there are multiple ways to achieve this. Let's discuss several methods to remove an item from a dict
3 min read
Python | Remove duplicates in Matrix
While working with Python Matrix, we can face a problem in which we need to perform the removal of duplicates from Matrix. This problem can occur in Machine Learning domain because of extensive usage of matrices. Let's discuss certain way in which this task can be performed. Method : Using loop This
2 min read
Python | Remove Initial K column elements
Sometimes, while working with Matrix data, we can have stray elements that attached at front end of each row of matrix. This can be undesired at times and wished to be removed. Letâs discuss certain ways in which this task can be performed. Method #1 : Using loop + del + list slicing The combination
4 min read
Python - Custom Rows Removal depending on Kth Column
Sometimes, while working with Python Matrix, we can have a problem in which we need to remove elements from Matrix depending on its Kth Column element present in the argument list. This can have application in many domains. Let us discuss certain ways in which this task can be performed. Method #1:
7 min read