Anonymous function lambda usage method, combined with map, apply and other usage methods

catalogue

1, Basic usage of lambda itself

1. Grammar

2. Characteristics

3. Examples

2, lambda combined with built-in functions (map,filter) and other uses

(1) python built-in map()

(2) python built-in filter()

3, lambda usage in numpy

(1) map() method

(2)numpy.apply_along_axis method

4, lambda usage in pandas

Lambda has its own usage, which is more combined with the use of built-in functions. This article introduces the method of combining the two functions. More importantly, the requirements of built-in functions for input functions are the requirements of lambda.

1, Basic usage of lambda itself

1. Grammar

In Python, the syntax of lambda is as follows:

lambda argument_list: expression

lambda is a keyword reserved by Python, and argument_list and expression are user-defined.

(1)argument_list is a parameter list. Its structure is the same as the parameter list of function in Python. For example:

x
a, b
a=1, b=2
*args      # The input is an arbitrary number of parameters (implicit requirement that the input parameters must be able to perform arithmetic operations)
**kwargs   # The input is an arbitrary key value pair parameter
a, b=1, *args
......

(2) Expression is an expression about parameters. The argument that appears in the expression needs to be in argument_list is defined, and the expression can only be single line. For example:

1
None
a + b
sum(a)  : sum()The variable in () is required to be iteratable, which is sum Determined by the function itself, for example, it can be a numeric list
1 if x== else 0

......

2. Characteristics

(1) lambda functions are anonymous: an anonymous function is a function without a name.

(2) lambda function has input and output: the input is passed into the parameter list argument_ The output is the value calculated according to the expression.

(3) Lambda functions are generally simple in function: single line expression determines that lambda functions cannot complete complex logic, but can only complete very simple functions.

3. Examples

catalogue

1, Basic usage of lambda itself

1. Grammar

2. Characteristics

3. Examples

2, lambda combined with built-in functions (map,filter) and other uses

  (1) python built-in map()

(2) python built-in filter()

3, lambda usage in numpy

(1) map() method

(2)numpy.apply_along_axis method

4, lambda usage in pandas

(1)map:

(2)apply:

(3)applymap()

in: lambda x : 5
out: <function __main__.<lambda>(x)>
# It can be found that this is a function. How can it be used alone? I think you can assign this to an object, and everything is an object

# Further demonstration
y = lambda x : 5 
y(4)
out:5
# Only the results are output here, but no variables are given

y = lambda x : x+5 
y(4)
out:9

# Assigning a variable is just a demonstration of its own method and process. Such a simple operation is not so useful in reality
y = lambda a,b : a*b 
c = y(5,6)
c
out:30

(2) Use in combination with built-in functions, such as sum. Of course, sum can also be replaced with any function, including custom functions, but pay attention to meet the requirements of the parameters of the function itself

y = lambda x : sum(x)
a = [1,2,3,4,5]
c = y(a)
c
out:15

(3) Use * args

y = lambda *args: sum(args)
y(3,2,1)
out:6
# Note the difference between this and the previous usage

(4) Use in combination with if and else.

Note that if and else may appear in pairs. I have tried many times. Only if without else keeps reporting errors

y = lambda x : 1  if x > 5  else 0
y(6)
out:1
y(2)
out:0

2, lambda combined with built-in functions (map,filter) and other uses

It is mainly to place the lambad function according to the requirements of the built-in function, and the data should meet the function requirements.

(1) python built-in map()

For example, the format of the map() function is:

Map (function, iteratable,...) the first parameter accepts a function name, and the following parameter accepts one or more iteratable sequences, and returns a set.

Then the lambda should be placed at the function of the map function, and the parameters behind the map should be placed in the iteratable object

a = ['1','2', 3, 4]
b = list(map(lambda x : float(x)  if type(x) == str else None, a)) # This function means that if the object is a string, it is converted to a numeric type
b
out:[1.0, 2.0, 3, 4]

(2) python built-in filter()

The function can filter some elements from the iteratable objects (such as dictionaries and lists) and generate a new iterator. An iteratable object is a Python object that can be "traversed", that is, it will return the elements in order, so that we can use it in the for loop.

The format of the filter() function is:

filter(function, iterable)

Returns an iteratable filter object, which can be converted into a list by using the list() function. This list contains all the items returned in the filter object.

a = [1, 2, 3, 6, 7]
y = filter(lambda x : x % 2 == 0, a)
list(y)    # You need to use list to get the value
out:[2, 6]

names = ['Sum', 'And', 'One', 'Two', 'Fore']
list(filter(lambda x: x[0] in 'SaT', names))    # x[0] is equivalent to string slicing for each element in the list
out:['Sum', 'Two']

3, lambda usage in numpy

You need to combine the map() method or NP apply_ along_ Axis(), which can only operate on one row or one column, and cannot operate on the entire multidimensional array, which is equivalent to operating on one-dimensional array

(1) map() method

It is easy to understand.

import numpy as np
arr = np.arange(15).reshape(3,5)
arr
out:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

arr[0]
out: array([0, 1, 2, 3, 4])

# The elements in the row of arr[0] in the array can be divided by 2 and returned
y = list(map(lambda x : 'BB' if x % 2 == 0 else 'AA' , arr[0]))
y
out:['BB', 'AA', 'BB', 'AA', 'BB']

# For comparison, x[0] operates on the column
y = list(map(0lambda x : 'BB' if x[0] %2==0 else 'AA' , arr))
y
out: ['AA', 'BB', 'AA']

(2)numpy.apply_along_axis method

Format:

numpy.apply_along_axis(function, axis, arr, *args, **kwargs)

Function: a new array formed by transforming each element of arr array through func function.

Parameter introduction: function, axis and arr are required. Function: is a function; Axis: indicates whether the function pair arr acts on a row or a column; Arr: array for operation; Optional parameters: * args, **kwargs. Are additional parameters of the function function.

Legacy problem: numpy has not found a method to operate on all elements, but it can use the index method in the user-defined function to define the operation of multiple columns on each row of the multidimensional array.

# Borrow the above data (arr)
# Example 1:
def f(x):
    if x[0] % 2 == 0 :
        return  'A'
    else :
        return  'B'

y = np.apply_along_axis(f, 0, arr)
y
out:array(['A', 'B', 'A', 'B', 'A'], dtype='<U1')
# Use lambda instead
y = np.apply_along_axis(lambda x : 'A' if x[0] % 2 == 0  else 'B', 0, arr)
y
out:array(['A', 'B', 'A', 'B', 'A'], dtype='<U1')

# Example 2:
def f(x):
     return (x[0]+x[1])
np.apply_along_axis(f, 1, arr)
out: array([ 1, 11, 21])

# Use lambda instead
y= np.apply_along_axis(lambda x: x[0] + x[1], 1, arr)
y
out: array([ 1, 11, 21])

4, lambda usage in pandas

Similar to numpy, it can be used in combination with * * map(), apply(), applymap() * * and other methods.

See the official website for specific usage of the three, such as: pandas.DataFrame.apply — pandas 1.4.3 documentation

(1)map:

Format: Series.map(*arg *, * na_action=None *)

map can only be used for Series.

The map is element wise, and the function is called once for each data in the Series; Map is mainly used to apply functions to each element of a Series.

import numpy as np
import pandas as pd
arr = np.arange(15).reshape(3,5)
a = pd.DataFrame(arr,columns=['A','B','C','D','E'])
a
out:
		A	B	C	D	E
		0	0	1	2	3	4
		1	5	6	7	8	9
		2	10	11	12	13	14

a['A'].map(lambda x :  "A" if x % 2 ==0 else "B")
out:
		0    A
		1    B
		2    A
		Name: A, dtype: object

a['A'].apply(lambda x :  "A" if x % 2 ==0 else "B")
out:
		0    A
		1    B
		2    A
		Name: A, dtype: object

(2)apply:

Format:

Series.apply(*func*, *convert_dtype=True*, *args=()*, ***kwargs*)

DataFrame.apply(*func*, *axis=0*, *raw=False*, *result_type=None*, *args=()*, ***kwargs*)

Not only for Series, but also for DataFrame;

When used for Series, if func returns a Series object, the result will be a DataFrame.

When used for DataFrame, the result applied along the given axis of the DataFrame is returned according to whether the axis parameter is a column or a row.

When map and apply are used in Series, each value is processed and the results are consistent. The difference between the two may be the difference in the requirements of input parameters.

In general, the application of apply in pandas is more flexible and extensive, especially when a user-defined function has multiple parameters, it is recommended to use apply.

a.apply(lambda x :  x.max(), axis=0)
out:
		A    10
		B    11
		C    12
		D    13
		E    14
		dtype: int64

a.apply(lambda x :  x.max(), axis=1)
out:
		0     4
		1     9
		2    14
		dtype: int64

a.apply(lambda x : x['A'] + x['B'],axis=1)
out:
		0     1
		1    11
		2    21
		dtype: int32

a.apply(lambda x : 'A'+ x.astype(str))
out:
			A	  B	  C	  D	  E
		0	A0	A1	A2	A3	A4
		1	A5	A6	A7	A8	A9
		2	A10	A11	A12	A13	A14

(3)applymap()

Format: DataFrame.applymap(*func *, * na_action=None *, * * * kwargs *)

When operating on each data of DataFrame, use applymap(), and the returned result is in DataFrame format

a.applymap(np.square)
out:
			A	B	C	D	E
		0	0	1	4	9	16
		1	25	36	49	64	81
		2	100	121	144	169	196

# AA is returned if it can be divided by 2, otherwise BB is returned
a.applymap(lambda x : "AA" if x % 2 == 0 else "BB")
out:
			A	  B	  C	  D	  E
		0	AA	BB	AA	BB	AA
		1	BB	AA	BB	AA	BB
		2	AA	BB	AA	BB	AA

# Convert each element into a string and take out the length
a.applymap(lambda x: len(str(x)))
out:
			A	B	C	D	E
		0	1	1	1	1	1
		1	1	1	1	1	1
		2	2	2	2	2	2

# Because applymap operates on each element, you cannot change the data type with astype, but you can use python methods.
# The following method is similar to a The results of apply (lambda x: 'a' + x.astype (STR)) were consistent
a.applymap(lambda x : 'A'+ str(x))
out:
			A	  B	  C	  D	  E
		0	A0	A1	A2	A3	A4
		1	A5	A6	A7	A8	A9
		2	A10	A11	A12	A13	A14

Tags: Python programming language

Posted by Lahloob on Tue, 16 Aug 2022 16:30:09 +0930