如何在Python-Pandas中获得一个数组值的元素的幂
让我们来看看如何获得一个数组值的元素的幂。Dataframe/Series.pow()用于计算元素与自身或与其他Series的幂。这个函数只适用于实数,对复数不提供结果。
因此,让我们看看这些项目。
例子1:一维数组被映射到pandas系列中,具有默认的数字索引或自定义索引,然后相应的元素被提升到它自己的幂。
# 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)
输出:
例子2:功率也可用于计算浮点小数。
# 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)
输出:
例子3: 多维数组可以被映射到pandas数据框中。然后,数据框架中的每个单元格都包含一个数字(整数或浮点数),它可以被提升到其各自的幂。
# 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)
输出: