pandas 面试题挑战十二
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')
输出
重点说明
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')
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')
输出