Python技术迷

Pandas 教程-Pandas DataFrame.transform

整理:python架构师

我们可以将Pandas DataFrame定义为一个二维的、大小可变的、异构的带有一些标记轴(行和列)的表格数据结构。执行算术运算将对齐行和列标签。它可以被视为Series对象的类似字典的容器。

Pandas DataFrame.transform() 函数的主要任务是生成一个具有其转换值的DataFrame,其轴长度与自身相同。

语法:

DataFrame.transform(func, axis=0, *args, **kwargs)

参数:

func:用于转换数据的函数。

axis:指的是0或'index',1或'columns',默认值为0。

*args:要传递给func的位置参数。

**kwargs:要传递给func的关键字参数。

专属福利 
👉点击领取:最全Python资料合集

返回值:

返回的DataFrame必须具有与自身相同的长度。

示例1:使用DataFrame.transform()函数将数据框中的每个元素加10。
# importing pandas as pd  importpandas as pd  # Creating the DataFrame  info =pd.DataFrame({"P":[8, 2, 9, None, 3],                       "Q":[4, 14, 12, 22, None],                       "R":[2, 5, 7, 16, 13],                       "S":[16, 10, None, 19, 18]})    # Create the index   index_ =['A_Row', 'B_Row', 'C_Row', 'D_Row', 'E_Row']   # Set the index   info.index =index_   # Print the DataFrame  print(info)
输出:
       P       Q        R       SA_Row 8.0      4.0      2.0    16.0B_Row  2.0     14.0    5.0     10.0C_Row  9.0     12.0    7.0     NaND_RowNaN   22.0    16.0   19.0E_Row  3.0NaN    13.0   18.0
示例2:使用DataFrame.transform()函数找到数据框中每个元素的平方根和euler数的结果。
# importing pandas as pd  importpandas as pd  # Creating the DataFrame  info =pd.DataFrame({"P":[8, 2, 9, None, 3],                       "Q":[4, 14, 12, 22, None],                       "R":[2, 5, 7, 16, 13],                       "S":[16, 10, None, 19, 18]})    # Create the index   index_ =['A_Row', 'B_Row', 'C_Row', 'D_Row', 'E_Row']   # Set the index   info.index =index_   # Print the DataFrame  print(info)
输出:
        P       Q       R       SA_Row  88.0     14.0    12.0    16.0B_Row  12.0     14.0    15.0     10.0C_Row  19.0     22.0    17.0     NaND_RowNaN     21.0    16.0    19.0E_Row  13.0NaN    13.0   18.0
Image
 1
Image
热门推荐
Image