Pandas2.2 DataFrame
Binary operator functions
方法 | 描述 |
---|---|
DataFrame.add(other) | 用于執行 DataFrame 與另一個對象(如 DataFrame、Series 或標量)的逐元素加法操作 |
DataFrame.add(other[, axis, level, fill_value]) | 用于執行 DataFrame 與另一個對象(如 DataFrame、Series 或標量)的逐元素加法操作 |
DataFrame.sub(other[, axis, level, fill_value]) | 用于執行逐元素的減法操作 |
DataFrame.mul(other[, axis, level, fill_value]) | 用于執行逐元素的乘法操作 |
DataFrame.div(other[, axis, level, fill_value]) | 用于執行逐元素的除法操作 |
DataFrame.truediv(other[, axis, level, …]) | 用于執行逐元素的真除法操作 |
DataFrame.floordiv(other[, axis, level, …]) | 用于執行逐元素的地板除法操作 |
DataFrame.mod(other[, axis, level, fill_value]) | 用于執行逐元素的取模操作 |
DataFrame.pow(other[, axis, level, fill_value]) | 用于對 DataFrame 中的元素進行冪運算 |
DataFrame.dot(other) | 用于計算兩個 DataFrame(或 DataFrame 與 Series/數組)之間的**矩陣點積(矩陣乘法)**的方法 |
pandas.DataFrame.dot()
pandas.DataFrame.dot(other)
是 Pandas 中用于計算兩個 DataFrame(或 DataFrame 與 Series/數組)之間的**矩陣點積(矩陣乘法)**的方法。它的行為類似于線性代數中的矩陣乘法,結果的行索引與原始 DataFrame 的行索引對齊,列索引與 other
的列索引對齊。
語法
DataFrame.dot(other)
- 參數
other
:可以是另一個 DataFrame、Series 或類數組結構(如 NumPy 數組)。 - 返回值:一個新的 DataFrame 或 Series,具體取決于輸入類型。
關鍵規則
- 維度對齊:調用方的列數必須與
other
的行數相等。 - 索引對齊:Pandas 會根據行/列標簽自動對齊數據。若標簽不匹配,可能導致 NaN 或錯誤。
- 與
*
的區別:df.dot(other)
是矩陣乘法,而df * other
是逐元素相乘。
示例
示例 1:DataFrame × DataFrame
import pandas as pd# 創建兩個 DataFrame
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}, index=['row1', 'row2'])
df2 = pd.DataFrame({'C': [5, 6], 'D': [7, 8]}, index=['A', 'B'])# 矩陣乘法:df1 的列索引(A, B)與 df2 的行索引(A, B)對齊
result = df1.dot(df2)
print(result)
輸出:
C D
row1 23 31
row2 34 46
計算過程:
row1
的結果:C = 1*5 + 3*6 = 5 + 18 = 23
D = 1*7 + 3*8 = 7 + 24 = 31
row2
的結果:C = 2*5 + 4*6 = 10 + 24 = 34
D = 2*7 + 4*8 = 14 + 32 = 46
示例 2:DataFrame × Series
import pandas as pddf = pd.DataFrame({'X': [1, 2, 3], 'Y': [4, 5, 6]}, index=['a', 'b', 'c'])
s = pd.Series([10, 20], index=['X', 'Y']) # Series 的索引與 df 的列對齊result = df.dot(s)
print(result)
輸出:
a 90 # 1*10 + 4*20 = 10 + 80 = 90
b 120 # 2*10 + 5*20 = 20 + 100 = 120
c 150 # 3*10 + 6*20 = 30 + 120 = 150
dtype: int64
示例 3:DataFrame × 數組
import pandas as pd
import numpy as npdf = pd.DataFrame({'M': [1, 2], 'N': [3, 4]})
arr = np.array([[5, 6], [7, 8]]) # 2x2 數組result = df.dot(arr)
print(result)
輸出:
0 1
0 26 30
1 38 44
計算過程:
- 第 0 行:
1*5 + 3*7 = 5 + 21 = 26
(列 0),1*6 + 3*8 = 6 + 24 = 30
(列 1) - 第 1 行:
2*5 + 4*7 = 10 + 28 = 38
(列 0),2*6 + 4*8 = 12 + 32 = 44
(列 1)
注意事項
- 維度不匹配:若列數 ≠
other
的行數,拋出ValueError
。 - 索引對齊問題:若標簽不匹配,可能生成 NaN。可用
.values
忽略索引:df1.dot(df2.values) # 使用純數值計算,忽略索引
- 與
@
運算符等價:df1 @ df2
與df1.dot(df2)
結果相同。
通過 dot()
方法,可以高效實現線性代數中的矩陣乘法操作,適用于數據分析、機器學習等場景。