美文网首页
pandas中map(),apply(),applymap()的

pandas中map(),apply(),applymap()的

作者: 数据小白周红艳 | 来源:发表于2020-09-02 10:03 被阅读0次

它们的区别在于应用的对象不同。map()是一个Series的函数,DataFrame结构中没有map()。map()将一个自定义函数应用于Series结构中的每个元素(elements)。

# 首先导入常用的两个包
import pandas as pd
import numpy as np
# 建立数据集
df = pd.DataFrame(np.random.randn(4, 2), columns=['a', 'b'])
df

        a         b
0   1.550585    0.613847
1   -0.065544   -0.021034
2   1.192564    -1.450901
3   -1.152545   0.538187

比如要将某一列的格式保留2位小数,下面这两种方式实现的效果是一样的

df['a_str']=df['a'].map(lambda x:'{:.2f}'.format(x))
df
# 结果:

        a           b       a_str
0   1.550585    0.613847    1.55
1   -0.065544   -0.021034   -0.07
2   1.192564    -1.450901   1.19
3   -1.152545   0.538187    -1.15
df['a_str']=df['a'].apply(lambda x:'{:.2f}'.format(x))
df
# 结果:
        a           b       a_str
0   1.550585    0.613847    1.55
1   -0.065544   -0.021034   -0.07
2   1.192564    -1.450901   1.19
3   -1.152545   0.538187    -1.15

注意,usage_time原来是folat类型,用了format格式化后,变成了str类型

image.png

可以给map传入一个字典映射

df = pd.DataFrame({'name':['小红','小明','小花'],'gender':[1,0,1]})
gender_map={1:'female',0:'male'}
df['gender_1']=df['gender'].map(gender_map)
image.png

applymap()将函数做用于DataFrame中的所有元素(elements),例如,在所有元素前面加个字符A

def add_a(x):
    x='a_'+str(x)
    return x
df.applymap(add_a)
image.png

相关文章

网友评论

      本文标题:pandas中map(),apply(),applymap()的

      本文链接:https://www.haomeiwen.com/subject/vijvjktx.html