lambda函数:匿名函数,即没有具体名称的函数,允许快速定义单行函数。
lambda 参数:操作运算
y=lambda x:x**2
print(y(10))#100
g=lambda x,y,z=3:(x+y)*z
print(g(1,2,5))#15
map(function, iterable)
第一个参数是传入一个函数,函数可内置,可自定义,可以是匿名函数。
第二个参数是一个可迭代对象,如列表,字符串等等。
返回一个map对象,注意不是列表不能直接输出,可通过for循环或者list()来显示。(python2返回的是列表)
map(lambda x:x**2,[1,2,3])#<map object at 0x000002BF6654F898>
list(map(lambda x:x**2,[1,2,3]))#[1, 4, 9]
[i**2 for i in [1,2,3]]#[1, 4, 9]
list(map(lambda x, y: x * y, [1, 3, 5, 7, 9], [2, 4, 6, 8]))
#参数长度不一,按照短的算[2, 12, 30, 56]
利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:[‘adam’, ‘LISA’, ‘barT’],输出:[‘Adam’, ‘Lisa’, ‘Bart’]:
list(map(lambda x:x[0].upper()+x[1:].lower(),['adam','LISA','barT']))
#['Adam', 'Lisa', 'Bart']
map用字典映射(dataframe的series,不能用list做字典映射?)
DataFrame->array->字典
import pandas as pd
#文件中有中文时
a = pd.read_csv('a.csv', encoding = 'gb2312')
a
mobile operator
0 155 移动
1 166 联通
2 129 未知
a.values
array([[155, '移动'],
[166, '联通'],
[129, '未知']], dtype=object)
<class 'numpy.ndarray'>
c=dict(a.values)
c
Out[7]: {155: '移动', 166: '联通', 129: '未知'}
b=pd.read_csv('b.csv')
b['m']=[int(str(i)[0:3]) for i in b['mobile']]
b
Out[8]:
mobile m
0 155636363 155
1 166342334 166
2 129442432 129
3 1312331232 131
4 15532341314 155
b['operator']=list(b['m'].map(c))
b
Out[11]:
mobile m operator
0 155636363 155 移动
1 166342334 166 联通
2 129442432 129 未知
3 1312331232 131 NaN
4 15532341314 155 移动
filter(function, iterable)
第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中,返回的是filter对象,用list显示。
#过滤偶数
list(filter(lambda x:x%2==0,list(range(10))))#[0, 2, 4, 6, 8]
#过滤100以内的完全平方数
import math
list(filter(lambda x:math.sqrt(x)%1==0,list(range(100))))
#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
series按列和索引排序
DataFrame按列和索引排序