How to use the lambda function In Python Pandas
In this example, we are taking a pandas data frame and one of the columns is an array of tuples, we can slice that particular column and apply a lambda function to extract a particular column from the tuple of an array.
Python3
import numpy as np import pandas as pd data = pd.DataFrame({ 'approval' : [ 10 , 20 , 30 , 40 , 50 ], 'temperature' : [( 18.18 , 2.27 , 3.23 ), ( 36.43 , 34.24 , 6.6 ), ( 5.25 , 6.16 , 7.7 ), ( 7.37 , 28.8 , 8.9 ), ( 12 , 23 , 3 )]}) res = data[ 'temperature' ]. apply ( lambda x: x[ 2 ]).values print (data) print (res) |
Output:
approval temperature 0 10 (18.18, 2.27, 3.23) 1 20 (36.43, 34.24, 6.6) 2 30 (5.25, 6.16, 7.7) 3 40 (7.37, 28.8, 8.9) 4 50 (12, 23, 3 The output for extracting 3rd column from the array of tuples [3.23 6.6 7.7 8.9 3. ]
How to extract a particular column from 1D array of tuples?
In this article, we will cover how to extract a particular column from a 1-D array of tuples in python.
Example
Input: [(18.18,2.27,3.23),(36.43,34.24,6.6),(5.25,6.16,7.7),(7.37,28.8,8.9)]
Output: [3.23, 6.6 , 7.7 , 8.9 ]
Explanation: Extracting the 3rd column from 1D array of tuples.