📜  Pandas 中 map、applymap 和 apply 方法的区别

📅  最后修改于: 2022-05-13 01:55:06.427000             🧑  作者: Mango

Pandas 中 map、applymap 和 apply 方法的区别

Pandas 库广泛用于数据操作和分析。 map()applymap()apply()方法是 Pandas 库的方法。

请注意,输出的类型完全取决于用作给定方法的参数的函数类型。

熊猫apply()方法:
此方法可用于 pandas 数据框和系列。作为参数传递的函数通常适用于行/列。下面的代码说明了apply()方法如何在 Pandas 数据帧上工作。

# Importing pandas library with an alias pd
import pandas as pd
   
# Dataframe generation
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')
   
# Using apply method for sorting 
# rows of characters present in 
# the original dataframe
new_gfg_df = gfg_df.apply(lambda x:x.sort_values(), axis = 1)
  
print("Transformed dataframe:\n" + \
       new_gfg_df.to_string(index = False,
            header = False), end = '\n\n')

输出:

下面的代码说明了如何在 Pandas 系列上apply()方法:

# Importing pandas library with an alias pd
import pandas as pd
   
# Series generation
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')
   
# Using apply method for converting characters
# present in the original series
new_gfg_series = gfg_series.apply(str.upper)
print("Transformed series:\n" + \
       new_gfg_series.to_string(index = False,
                header = False), end = '\n\n')

输出:


熊猫applymap()方法:
此方法可用于 pandas 数据帧。作为参数传递的函数通常适用于数据框的元素applymap()通常用于元素操作。下面的代码说明了applymap方法如何在 pandas 数据帧上工作:

# Importing pandas library with an alias pd
import pandas as pd
   
# DataFrame generation
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')
   
# Using applymap method for transforming 
# characters into uppercase characters 
# present in the original dataframe
new_gfg_df = gfg_df.applymap(str.upper)
print("Transformed dataframe:\n" + \
       new_gfg_df.to_string(index = False,
            header = False), end = '\n\n')

输出:

熊猫map()方法:
此方法用于作为参数传递的系列函数、列表和字典。此方法通常用于映射来自具有相同列的两个系列的值。下面的代码说明了map方法如何在 pandas 系列上工作:

# Importing pandas library with an alias pd
import pandas as pd
   
# Series generation
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')
   
# Using apply method for converting characters
# present in the original series
new_gfg_series = gfg_series.map(str.upper)
print("Transformed series:\n" + \
       new_gfg_series.to_string(index = False,
                header = False), end = '\n\n')

输出: