Python Map, filter, and reduce functions
- map
- filter
- reduce
- apply
1. map
Python3.* returns an iterator (filter), and a filter (filter) returns a list conversion call: The map (function, iterable1 iterable2), the function of the parameter value is not necessarily a x, or x and y, even more. The iterable that follows represents the parameter values that are required to participate in the function operation, passing in as many iterable values as possible
X = y =,3,4,5,6 [2] [1, 2, 3, 4, 5] list (map (lambda x, y (x * y) + 2, x, y)) # output: [4, 8, 14, 22, 32] # note: If several sequences are passed in a map with different lengths, the shortest sequence is computed.Copy the code
2filter
Function: The function of filter is to filter out the elements that do not meet the function conditions. When the elements to be deleted from the sequence can be described by some functions, the filter function should be used. Call filter (function, sequence). Function can be an anonymous function or a custom function. This function checks whether each element of the sequence meets the function condition and returns TRUE or FALSE, leaving only TRUE elements. Sequence can be a list, a tuple, or a string example:
X = [1, 2, 3, 4, 5] list (filter (lambda x: x % 2 = = 0, x)) # to find even. After python3.*, the filter function returns an iterator instead of a list, so a list conversion is required. # output: [2, 4]Copy the code
3 reduce
Function: Compress a sequence to obtain a value. But reduce was a built-in function in Python2 and was moved to the functools module in Python3, so the call from functools import reduce is required before using it: Reduce (function, iterable), where function must take two arguments. Iterable can be a list or a tuple:
From functools import reduce y = [2,3,4,5,6] reduce(lambda x,y: x + y,y) # return a value directlyCopy the code
The calculation principle is as follows: calculate the first two elements: F (2, 3), the result is 5; Add the result to the third element: f(5, 4), which is 9; Add the result to the fourth element: f(9, 5), and the result is 14. Add the result to the fifth element: f(14, 6), which is 20; Since there are no more elements, the calculation is finished and the result is 20.
4 apply
Pandas is a DataFrame or Series function in pandas. The function applies directly to the DataFrame or Series in pandas, and applies to the aggregate object after groupBY in pandas: Apply (function,axis), function indicates the function to be used,axis indicates the row or column to operate on examples:
import numpy as np import pandas as pd a = np.random.randint(low=0, high=4, Size =(2,4)) data = pd.dataframe (a) d = data.apply(lambda x:x*10) # print(d) # print(d) # print: 0 1 2 30 30 0 0 10 1 30 10 30 20 ""Copy the code
The functools module “reduce” and the “apply” module “pandas” are used to filter and delete sequences. To perform functions on multiple sequences, use map; In pandas, call apply directly