通过map函数和replace函数都可以对dataframe某一列的值进行批量修改,但今天运用是发现两者存在差别:

背景:存在一个df,需要将animal列当中的snake修改为python

#生成dataframe
data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
        'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],
        'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(data,index=labels)

 (1)使用replace函数

没有出现异常,正常完成了替换

(2)使用map函数

除了值为snake的替换为python,其余值全部变为nan

总结(个人推断):map是作用于元素级别的函数,会对animal列里的每一个元素执行map当中的语句,语句当中没有包含的值,只能返回NaN。

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐