📜  Python| Pandas DataFrame.transform

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

Python| Pandas DataFrame.transform

Pandas DataFrame 是一种二维大小可变的、潜在异构的表格数据结构,带有标记的轴(行和列)。算术运算在行标签和列标签上对齐。它可以被认为是 Series 对象的类 dict 容器。这是 Pandas 的主要数据结构。

Pandas DataFrame.transform()函数在 self 上调用 func 生成一个具有转换值的 DataFrame,并且与 self 具有相同的轴长度。

示例 #1:使用DataFrame.transform()函数将 10 添加到数据框中的每个元素。

# importing pandas as pd
import pandas as pd
  
# Creating the DataFrame
df = pd.DataFrame({"A":[12, 4, 5, None, 1], 
                   "B":[7, 2, 54, 3, None], 
                   "C":[20, 16, 11, 3, 8], 
                   "D":[14, 3, None, 2, 6]}) 
  
# Create the index
index_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']
  
# Set the index
df.index = index_
  
# Print the DataFrame
print(df)

输出 :

现在我们将使用DataFrame.transform()函数为数据帧的每个元素添加 10。

# add 10 to each element of the dataframe
result = df.transform(func = lambda x : x + 10)
  
# Print the result
print(result)

输出 :

正如我们在输出中看到的那样, DataFrame.transform()函数已成功为给定 Dataframe 的每个元素添加了 10。示例 #2 :使用DataFrame.transform()函数查找平方根以及对数据帧的每个元素求欧拉数的结果。

# importing pandas as pd
import pandas as pd
  
# Creating the DataFrame
df = pd.DataFrame({"A":[12, 4, 5, None, 1], 
                   "B":[7, 2, 54, 3, None], 
                   "C":[20, 16, 11, 3, 8], 
                   "D":[14, 3, None, 2, 6]}) 
  
# Create the index
index_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']
  
# Set the index
df.index = index_
  
# Print the DataFrame
print(df)

输出 :

现在我们将使用DataFrame.transform()函数来找到平方根和欧拉数对数据帧的每个元素的结果。

# pass a list of functions
result = df.transform(func = ['sqrt', 'exp'])
  
# Print the result
print(result)

输出 :

正如我们在输出中看到的那样, DataFrame.transform()函数已经成功地对给定的数据帧执行了所需的操作。