📌  相关文章
📜  如何在 Python-Pandas 中逐元素获取数组值的权力?

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

如何在 Python-Pandas 中逐元素获取数组值的权力?

让我们看看如何按元素获取数组值的幂。 Dataframe/Series.pow()用于计算元素本身或提供的其他系列的功率。此函数仅适用于实数,不给出复数的结果。
那么让我们看看这些程序:

示例 1:将一维数组映射到具有默认数字索引或自定义索引的 pandas 系列然后将相应的元素提升到自己的幂。

Python3
# import required modules
import numpy as np
import pandas as pd 
  
# create an array
sample_array = np.array([1, 2, 3])  
  
# uni dimensional arrays can be
# mapped to pandas series
sr = pd.Series(sample_array) 
  
print ("Original Array :")
print (sr)
  
# calculating element-wise power 
power_array = sr.pow(sr)
  
print ("Element-wise power array")
print (power_array)


Python3
# module to work with arrays in python
import array
  
# module required to compute power
import pandas as pd
  
# creating a 1-dimensional floating 
# point array containing three elements
sample_array = array.array('d', 
                           [1.1, 2.0, 3.5])  
  
# uni dimensional arrays can 
# be mapped to pandas series
sr = pd.Series(sample_array) 
  
print ("Original Array :")
print (sr)
  
# computing power of each 
# element with itself 
power_array = sr.pow(sr)
  
print ("Element-wise power array")
print (power_array)


Python3
# module to work with 
# arrays in python
import array
  
# module required to 
# compute power
import pandas as pd
  
# 2-d matrix containing 
# 2 rows and 3 columns
df = pd.DataFrame({'X': [1,2],
                   'Y': [3,4],
                   'Z': [5,6]});
  
print ("Original Array :")
print(df)
  
# power function to calculate
# power of data frame elements
# with itself
power_array = df.pow(df)
  
print ("Element-wise power array")
print (power_array)


输出:

逐元素功率阵列

示例 2:也可以计算浮点十进制数的幂。

Python3

# module to work with arrays in python
import array
  
# module required to compute power
import pandas as pd
  
# creating a 1-dimensional floating 
# point array containing three elements
sample_array = array.array('d', 
                           [1.1, 2.0, 3.5])  
  
# uni dimensional arrays can 
# be mapped to pandas series
sr = pd.Series(sample_array) 
  
print ("Original Array :")
print (sr)
  
# computing power of each 
# element with itself 
power_array = sr.pow(sr)
  
print ("Element-wise power array")
print (power_array)

输出:

逐元素功率阵列 - 1

示例 3: 多维数组可以映射到 pandas 数据帧。然后,数据框包含每个包含数字(整数或浮点数)的单元格,可以将其提升到自己的单独幂。

Python3

# module to work with 
# arrays in python
import array
  
# module required to 
# compute power
import pandas as pd
  
# 2-d matrix containing 
# 2 rows and 3 columns
df = pd.DataFrame({'X': [1,2],
                   'Y': [3,4],
                   'Z': [5,6]});
  
print ("Original Array :")
print(df)
  
# power function to calculate
# power of data frame elements
# with itself
power_array = df.pow(df)
  
print ("Element-wise power array")
print (power_array)

输出:

逐元素功率阵列 - 2