The Wayback Machine - https://web.archive.org/web/20240927173509/https://www.geeksforgeeks.org/python-get-kth-column-of-matrix/
Open In App

Python | Get Kth Column of Matrix

Last Updated : 17 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Sometimes, while working with Python Matrix, one can have a problem in which one needs to find the Kth column of Matrix. This is a very popular problem in Machine Learning Domain and having solution to this is useful. Let’s discuss certain ways in which this problem can be solved. 

Method #1 : Using list comprehension This problem can be solved using list comprehension in which we can iterate through all the rows and selectively gather all the elements occurring at Kth index. 

Python3




# Python3 code to demonstrate working of
# Get Kth Column of Matrix
# using list comprehension
 
# initialize list
test_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize K
K = 2
 
# Get Kth Column of Matrix
# using list comprehension
res = [sub[K] for sub in test_list]
 
# printing result
print("The Kth column of matrix is : " + str(res))


Output : 

The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
The Kth column of matrix is : [6, 10, 5]

Time complexity: O(n), where n is the number of elements in the matrix.
Auxiliary space: O(1), as only constant space is used to store the input matrix and the integer K.

Method #2 : Using zip() This task can also be performed using zip(). This does the similar task of gathering elements like is done by above list comprehension and offers compact but slower execution. Works with Python2 only. 

Python




# Python code to demonstrate working of
# Get Kth Column of Matrix
# using zip()
 
# initialize list
test_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize K
K = 2
 
# Get Kth Column of Matrix
# using zip()
res = list(zip(*test_list)[K])
 
# printing result
print("The Kth column of matrix is : " + str(res))


Output : 

The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
The Kth column of matrix is : [6, 10, 5]

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Method #3: Using numpy

Note: First Install numpy module using command “pip install numpy”

This problem can also be solved using numpy library which provides a very efficient and easy way to get the Kth column of matrix.

Python3




import numpy as np
# initialize list
test_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
# printing original list
print("The original list is : " + str(test_list))
#initialize K
K = 2
# Get Kth Column of Matrix
# using numpy
res = np.array(test_list)[:,K]
# printing result
print("The Kth column of matrix is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output:

The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
The Kth column of matrix is : [ 6 10  5]

Time Complexity: O(n*n), where n is the length of the list test_list 
Auxiliary Space: O(n) where n is the length of the list test_list 

Method 4: Using a for loop.

This code uses a for loop to iterate over the rows of the matrix and extract the Kth element from each row using indexing. The extracted elements are then appended to a new list called res. The final output is the list res containing the Kth column of the matrix.

Python3




test_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
 
K = 2
 
res = []
 
for i in range(len(test_list)):
    res.append(test_list[i][K])
 
print("The Kth column of matrix is : " + str(res))


Output

The Kth column of matrix is : [6, 10, 5]

Time complexity: O(n), where n is the number of rows in the matrix.
Auxiliary space:  O(n), because the list “res” will have at most n elements.

Method #6: Using the built-in function map()

Use the map() function to apply a lambda function that extracts the Kth element from each sublist in the matrix. The resulting map object is then converted to a list to obtain the final result.

Python3




# initialize list
test_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize K
K = 2
 
# Get Kth Column of Matrix using map()
res = list(map(lambda x: x[K], test_list))
 
# printing result
print("The Kth column of matrix is : " + str(res))


Output

The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
The Kth column of matrix is : [6, 10, 5]

The time complexity of this code is O(n), where n is the total number of elements in the input matrix.
The space complexity of this code is O(n), where n is the total number of elements in the input matrix. 

Method 6: Using list slicing

Step-by-step approach:

  1. Initialize the list to store the kth column of the matrix
  2. Loop through each row in the matrix
  3. Append the element at index k of the row to the list initialized in step 1
  4. Return the list as the kth column of the matrix

Below is the implementation of the above approach:

Python3




# Python code to demonstrate working of
# Get Kth Column of Matrix
# using list slicing
 
# initialize list
test_list = [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize K
K = 2
 
# Get Kth Column of Matrix
# using list slicing
res = [row[K] for row in test_list]
 
# printing result
print("The Kth column of matrix is : " + str(res))


Output

The original list is : [[4, 5, 6], [8, 1, 10], [7, 12, 5]]
The Kth column of matrix is : [6, 10, 5]

Time complexity: O(n), where n is the number of elements in the matrix.
Auxiliary space: O(n), where n is the number of elements in the matrix.



Previous Article
Next Article

Similar Reads

Python - Summation of kth column in a matrix
Sometimes, while working with Python Matrix, we may have a problem in which we require to find the summation of a particular column. This can have a possible application in day-day programming and competitive programming. Let’s discuss certain ways in which this task can be performed. Method #1 : Using sum() + zip() This task can be solved using th
8 min read
Python - Reverse sort Matrix Row by Kth Column
Sometimes, while working with data, we can have a problem in which we need to perform sorting of each row of records by some of decisive factor like score. This kind of problem is common in competitive programming and web development. Lets discuss certain ways in which this task can be performed. Method #1 : Using sorted() + lambda + reverse The co
4 min read
Get Column name and Column type with Python psycopg2
When working with PostgreSQL databases in Python, one common task is to retrieve metadata about database tables, such as column names and their types. This information can be crucial for dynamically generating queries, validating data, or understanding the structure of our database. The psycopg2 library provides a powerful way to interact with Post
4 min read
Python Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
Get column index from column name of a given Pandas DataFrame
In this article we will see how to get column index from column name of a Dataframe. We will use Dataframe.columns attribute and Index.get_loc method of pandas module together. Syntax: DataFrame.columns Return: column names index Syntax: Index.get_loc(key, method=None, tolerance=None) Return: loc : int if unique index, slice if monotonic index, els
2 min read
Python - Consecutive Kth column Difference in Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the absolute difference of it’s Kth index. This problem has application in web development domain while working with data informations. Let’s discuss certain ways in which this task can be performed. Examples: Input : test_list = [(5, 4, 2
6 min read
Python | Summation of Kth Column of Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the possible accumulation of its Kth index. This problem has applications in the web development domain while working with data information. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehensio
7 min read
Python | Product of kth column in List of Lists
Sometimes, while working with Python Matrix, we may have a problem in which we require to find the product of a particular column. This can have a possible application in day-day programming and competitive programming. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop + zip() This task can be solved using the c
4 min read
Python - Kth Column Product in Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the product of it’s Kth index. This problem has application in web development domain while working with data informations. Let’s discuss certain ways in which this task can be performed. Method #1: Using list comprehension + loop This tas
7 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: Using loop This is a brute way in which this task
7 min read
Python - Group records by Kth column in List
Sometimes, while working with Python lists, we can have a problem in which we need to perform grouping of records on basis of certain parameters. One such parameters can be on the Kth element of Tuple. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + defaultdict() The combination of above methods can be used t
8 min read
Python - Remove Rows for similar Kth column element
Given a Matrix, remove row if similar element has occurred in row above in Kth column. Input : test_list = [[3, 4, 5], [2, 3, 5], [10, 4, 3], [7, 8, 9], [9, 3, 6]], K = 2 Output : [[3, 4, 5], [10, 4, 3], [7, 8, 9], [9, 3, 6]] Explanation : In [2, 3, 5], we already has list [3, 4, 5] having 5 at K, i.e 2nd pos. Input : test_list = [[3, 4, 5], [2, 3,
7 min read
Python - Extract ith column values from jth column values
Sometimes, while working with Python Matrix, we can have a problem in which we need to extract ith column values from comparing values from jth column. This kind of problem can occur in domains such as school programming or web development. Let's discuss certain ways in which this task can be performed. Input : test_list = [[4, 5, 6], [2, 5, 7], [9
8 min read
Python - Scaling numbers column by column with Pandas
Scaling numbers in machine learning is a common pre-processing technique to standardize the independent features present in the data in a fixed range. When applied to a Python sequence, such as a Pandas Series, scaling results in a new sequence such that your entire values in a column comes under a range. For example if the range is ( 0 ,1 ) your e
3 min read
Python | Get Kth element till N
Sometimes, we may come across a utility in which we require to get the first N sublist elements that too only a particular index. This can have an application in queuing to get only the Kth N person’s name. Let’s discuss certain ways in which this can be done. Method #1 : Using list comprehension and list slicing The above two powerful Python utili
3 min read
Python Program to get the Longest Alphabetic order of Kth index from list values
Given a string list, the task is to write a Python program to extract Strings that form the longest increasing alphabetic order at the Kth index. K should be less than the minimum length of all strings. Input : test_list = ["gfg", "is", "best", "for", "geeks", "and", "cs"], K = 0 Output : ['best', 'for', 'geeks'] Explanation : Longest subsequence e
4 min read
Python Program to Reverse Every Kth row in a Matrix
Given a Matrix, the task is to write a python program to reverse every Kth row. Where K is some span value. Input : test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]], K = 4 Output : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [6, 3], [3, 7, 4], [2, 9]] Explanation : Every 4th row is reversed.Input : test_list = [[5, 3, 2], [8, 6, 3], [
6 min read
Create a DataFrame from a Numpy array and specify the index column and column headers
Let us see how to create a DataFrame from a Numpy array. We will also learn how to specify the index and the column headers of the DataFrame. Approach : Import the Pandas and Numpy modules. Create a Numpy array. Create list of index values and column values for the DataFrame. Create the DataFrame. Display the DataFrame. Example 1 : # importiong the
2 min read
Create a Pandas DataFrame from a Numpy array and specify the index column and column headers
This article demonstrates multiple examples to convert the Numpy arrays into Pandas Dataframe and to specify the index column and column headers for the data frame. Example 1: In this example, the Pandas dataframe will be generated and proper names of index column and column headers are mentioned in the function. This approach can be used when ther
4 min read
How to add column sum as new column in PySpark dataframe ?
In this article, we are going to see how to perform the addition of New columns in Pyspark dataframe by various methods. It means that we want to create a new column that will contain the sum of all values present in the given row. Now let's discuss the various methods how we add sum as new columns But first, let's create Dataframe for Demonstratio
4 min read
Drop a column with same name using column index in PySpark
In this article, we are going to learn how to drop a column with the same name using column index using Pyspark in Python. Pyspark offers you the essential function 'drop' through which you can easily delete one or more columns. But have you ever got the requirement in which you have various columns with the same column names and the requirement is
3 min read
Number from a given range that requires Kth smallest number of steps to get reduced to 1
Given three positive integers L, R, and K, the task is to find the number from the range [L, R] which requires Kth smallest number of steps to be reduced to 1 by performing the following operations: If X is even, then reduce X to X/2.Otherwise, set X = (3*X + 1). Examples: Input: L = 7, R = 10, K = 4Output: 9Explanation: Count of steps for all the
9 min read
How to Get the Minimum and maximum Value of a Column of a MySQL Table Using Python?
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to get the Minimum and Maximum Value of a Column of a MySQL Table Using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an
2 min read
Python - Get maximum of Nth column from tuple list
Sometimes, while working with Python lists, we can have a task in which we need to work with tuple list and get the maximum of its Nth index. This problem has application in web development domain while working with data information. Let’s discuss certain ways in which this task can be performed. Method #1: Using list comprehension + max() This tas
7 min read
Python - Get Nth column elements in Tuple Strings
Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the Nth index element of each string in tuple. Let’s d
8 min read
Get the substring of the column in Pandas-Python
Now, we'll see how we can get the substring for all the values of a column in a Pandas dataframe. This extraction can be very useful when working with data. For example, we have the first name and last name of different people in a column and we need to extract the first 3 letters of their name to create their username. Example 1: We can loop throu
2 min read
Get the data type of column in Pandas - Python
Let’s see how to get data types of columns in the pandas dataframe. First, Let’s create a pandas dataframe. Example: C/C++ Code # importing pandas library import pandas as pd # List of Tuples employees = [ ('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 3
3 min read
Get column names from CSV using Python
CSV stands for Comma Separated Values and CSV files are essentially text files which are used to store data in a tabular fashion using commas (,) as delimiters. CSV is a file format and all the files of this format are stored with a .csv extension. It is a very popular and extensively used format for storing the data in a structured form. CSV files
3 min read
Python SQLAlchemy - Get column names dynamically
In this article, we are going to see how to dynamically get the column names of a table in SQLAlchemy using Python. Used database for demonstration: So, our student table has 5 columns namely sno, name, dob, class, and section, and our task is to fetch all these column names in our Python code. First of all, we will import the sqlalchemy module, cr
2 min read
Get values of all rows in a particular column in openpyxl - Python
In this article, we will explore how to get the values of all rows in a particular column in a spreadsheet using openpyxl in Python. We will start by discussing the basics of openpyxl and how to install and import it. Then, we will walk through for example, how to extract the values of a particular column from a spreadsheet and store them in a list
4 min read