Four advanced functions of Python data analysis

Anonymous function

  • No need to use def to define functions
  • No specific name
  • Use lambda to define functions
  • Grammatical structure: lambda par1, par2, ... parn: expression

Examples

#冒号前面是参数,冒号后面是表达式,也是所要返回的结果
g = lambda x:x**2
g(2)

Insert picture description here

map function

The map () method maps a function to each element of the sequence to generate a new sequence, including all function return values. Broadly speaking, each element in the sequence is treated as an x ​​variable and put into a function f (x), and the result is a new sequence of f (x1), f (x2), f (x3) ...

  • The map function returns an iterator
  • Call method:
    map (function, list_input)
    function represents the function
    list_input represents the input sequence

Examples

#定义一个列表
items = [1,2,3,4,5,6]
def f(x):
	return x**2
map(f,items)
list(map(f,items))

Insert picture description here

reduce function

Definition:
During the iteration sequence, the first two elements (only two) are passed to the function. After the function is processed, the result and the third element are then passed to the function as two parameters. By analogy, it's like finding the cumulative sum of 1-100

  • The reduce function is not a built-in function, so you must import a third-party library
  • The reduce function cannot be used directly
  • reduce (function, iterable)
    function: representative function
    iterable: sequence

Examples

from functools import reduce
def f(x,y):
	return x + y
items = [1,2,3,4,5,6,7,8,9,10]
result = reduce(f,items)
result
#求1-100累加和
items = range(1,101)
result = reduce(f,items)
result

Insert picture description here
Insert picture description here

filter function

  • Used to filter sequences, filter out elements that do not meet the conditions, and return a sequence of elements that meet the conditions
  • Function will be applied to each item of sequence in sequence, that is, function (item), and the item whose return value is True will form a list / string / tuple (depending on the type of sequence)
  • Python3 unified return iterator

Examples

filter(lambda x:x%2==0,range(21))
list(filter(lambda x:x%2==0,range(21)))

Insert picture description here

items = [1,2,3,4,'3263','chen','-34.56',45.8]
list(filter(lambda x:1 if isinstance(x,int)else 0,items))

Insert picture description here
or:

def int_num(x):
	if isinstance(x,int):
		return True
	else:
		return False
list(filter(int_num,items))

Insert picture description here

Published 26 original articles · praised 5 · visits 777

Guess you like

Origin blog.csdn.net/weixin_44730235/article/details/104924020