pandas 面试题挑战十二

DataFrame中的apply方法,applymap方法有什么区别

DataFrame中的apply方法

import pandas as pd 
   
# 生成DF数据
gfg_string = 'geeksforgeeks'
gfg_list = 5 * [pd.Series(list(gfg_string))] 
   
gfg_df = pd.DataFrame(data = gfg_list)
print("Original dataframe:\n" + gfg_df.to_string(index = False,  header = False), end = '\n\n') 
   
#调用apply方法
new_gfg_df = gfg_df.apply(lambda x:x.sort_values(), axis = 1)  
#每次处理df中的一列,也就是一个Series

print("Transformed dataframe:\n" +  
      new_gfg_df.to_string(index = False, 
           header = False), end = '\n\n') 

输出


image.png

重点说明
df中的apply方法默认的处理一列。

DataFrame中的applymap方法


import pandas as pd 
   
# DataFrame 数据如下
gfg_string = 'geeksforgeeks'
gfg_list = 5 * [pd.Series(list(gfg_string))] 
gfg_df = pd.DataFrame(data = gfg_list) 
  
print("Original dataframe:\n" +  
       gfg_df.to_string(index = False, 
        header = False), end = '\n\n') 
   
#  applymap 方法
new_gfg_df = gfg_df.applymap(str.upper) 
#new_gfg_df = gfg_df.applymap(lambda x: print("me:{}".format(x)))  
#在DF中每次处理一个元素
print("Transformed dataframe:\n" +  
      new_gfg_df.to_string(index = False, 
            header = False), end = '\n\n') 
image.png

Series中的apply方法

Series中的apply方法


import pandas as pd 
   
# Series 数据
gfg_string = 'geeksforgeeks'
gfg_series = pd.Series(list(gfg_string)) 
print("Original series\n" + 
       gfg_series.to_string(index = False, 
            header = False), end = '\n\n') 
   

#apply每次处理一个元素
new_gfg_series = gfg_series.apply(str.upper) 
print("Transformed series:\n" +  
       new_gfg_series.to_string(index = False, 
                header = False), end = '\n\n') 

输出


image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容