Python中的那些内置函数【待续】

1. lambda函数

又叫匿名函数,也就是这个函数不像 "def calculate():" 这样的函数有具体的名称,其形式为:lambda 参数:操作

lambda函数的优势是允许快速的定义单行的简单的函数,可以在任何需要函数的地方

# 单个参数的:
g = lambda x : x ** 2
print g(3)
"""
9
"""
# 多个参数的:
g = lambda x, y, z : (x + y) ** z
print g(1,2,2)
"""
9
"""

# 与map函数一起用
map( lambda x: x*x, [y for y in range(4)] )
"""
0 1 4 9
"""

 

2. apply函数

apply函数的用法为:apply(func, *args, **kwargs),其中func可以是匿名函数

apply与map的区别就是apply作用在一维的向量上,而map将函数作用于一个Series的每一个元素

# apply与一般函数结合
def function(a,b):  
    print(a,b)
apply(function,('good','better'))  
apply(function,('cai',),{'b':'caiquan'})  
apply(function,(),{'a':'caiquan','b':'Tom'})

"""
('good', 'better')
('cai', 'caiquan')
('caiquan', 'Tom')
"""

# apply与匿名函数结合
all_data["City"]=all_data["Purchase Address"].apply(lambda x: x.split(',')[1])

3. map函数

map函数就是将函数作用与一个Series上的每一个元素

map( lambda x: x*x, [y for y in range(4)] )
"""
0 1 4 9
"""

4. applymap函数

如果想让方程作用于DataFrame中的每一个元素,可以使用applymap()

5. 格式化字符串的简单使用

f-string用大括号 {} 表示被替换字段,其中直接填入替换内容:

>>> name = 'Eric'
>>> f'Hello, my name is {name}'
'Hello, my name is Eric'

>>> number = 7
>>> f'My lucky number is {number}'
'My lucky number is 7'

>>> price = 19.99
>>> f'The price of this book is {price}'
'The price of this book is 19.99'

猜你喜欢

转载自blog.csdn.net/weixin_43450646/article/details/108987539
今日推荐