pandas 面試題挑戰(zhàn)十二

DataFrame中的apply方法,applymap方法有什么區(qū)別

DataFrame中的apply方法

import pandas as pd 
   
# 生成DF數(shù)據(jù)
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') 
   
#調(diào)用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方法默認(rèn)的處理一列。

DataFrame中的applymap方法


import pandas as pd 
   
# DataFrame 數(shù)據(jù)如下
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 數(shù)據(jù)
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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容