如何求两个pandas Series对象的点积?
Pandas中的series.dot()方法用于执行两个pandas Series对象的点积运算。在数学中,两个序列的点积由每个序列中值的乘积之和给出。
series.dot()只接受一个参数,另一个对象,它接受一个Series或类似数组的对象,以执行每个对象元素之间的点积。
示例1
# import pandas packages import pandas as pd # Creating Series objects series1 = pd.Series([1, 0, 5, 2]) print('First series object:',series1) series2 = pd.Series([3, 7, 2, 9]) print('second series object:',series2) print("Dot product of Series1 and Series2:", series1.dot(series2))
解释
首先,我们使用Python整数列表创建了两个pandas Series对象。然后在两个Series对象series1和series2的元素之间应用点积。
输出
First series object: 0 1 1 0 2 5 3 2 dtype: int64 second series object: 0 3 1 7 2 2 3 9 dtype: int64 Dot product of Series1 and Series2: 31
给定示例的点积为31,给定的Series对象具有相同数量的元素和相同的索引标签。如果两个Series对象的标签不同,则会引发错误。因此,我们必须为两个Series对象提供相同的索引标签。
示例2
# import pandas packages import pandas as pd # Creating Series objects series1 = pd.Series([71, 53, 84, 10], index=['A', 'B', 'C', 'D']) print('First series object:',series1) series2 = pd.Series([9, 27, 42, 38], index=['A', 'B', 'C', 'D']) print('second series object:',series2) print("Dot product of Series1 and Series2:", series1.dot(series2))
解释
首先,我们创建了两个具有特定索引标签的pandas Series对象。之后,我们在这两个Series对象之间应用点积。
输出
First series object: A 71 B 53 C 84 D 10 dtype: int64 second series object: A 9 B 27 C 42 D 38 dtype: int64 Dot product of Series1 and Series2: 5978
series.dot()方法返回一个值,表示两个Series对象的点积。对于以下示例,点积值为“5978”。
广告