因为我主要是将其用于DataFrame数据中,所以我们可以这么认为
- map(Series)—>对某列进行操作
- apply(DataFrame)—>对行数据或者列数据进行操作
- applymap(DataFrame)—>对所有表中元素进行操作
一,map
- 在python2中map返回的是一个列表,而在python3中返回的是一个迭代器,如果获取转换为 list 就行了
import pandas as pd
import numpy as np
temp = {"name":["一","二","三","四","五"],"年龄":[10,5,17,5,17],"num":[5,500,10000,700,8000]}
a = pd.DataFrame(temp)
def square(x) :
return x ** 2
a["年龄"] = list(map(square,a["年龄"]))
a["年龄"].map(lambda x: x ** 2)
print(a)
二,apply
- axis = 0 作用在列上,默认
- axis = 1 作用在行上
import pandas as pd
import numpy as np
temp = {"name":["一","二","三","四","五"],"年龄":[10,5,17,5,17],"num":[5,500,10000,700,8000]}
a = pd.DataFrame(temp)
def xiugai(x) :
return str(x)+"修改"
a["年龄"] = a["年龄"].apply(xiugai )
print(a)
def xiugai(x) :
return str(x)+"修改"
a.iloc[0] = a.iloc[0].apply(xiugai )
print(a)
a["年龄"] = a["年龄"].apply(lambda x:str(x) + "修改")
print(a)
a.iloc[0] = a.iloc[0].apply(lambda x:str(x) + "修改")
print(a)
def testf(x, str):
return x,str
a["name"] = a["name"].apply(testf, args=("ok",))
print(a)
三,applymap
import pandas as pd
import numpy as np
temp = {"name":["一","二","三","四","五"],"年龄":[10,5,17,5,17],"num":[5,500,10000,700,8000]}
a = pd.DataFrame(temp)
def xiugai(x) :
return str(x)+"修改"
a = a.applymap(xiugai )
print(a)
a = a.applymap(lambda x:str(x) + "修改")
print(a)
|