[英]element-wise product matrix x matrix
如何按列進行逐元素產品,我正在尋找一種非循環技術,因為我在每個數據幀中有幾十列並且寬度大小不同
例子:
mat1=pd.DataFrame({"a":[1,1,1],"b":[2,2,2]})
mat2=pd.DataFrame({"c":[1,1,1],"d":[1,2,3]})
輸出
ac ad bc bd
0 1 1 2 2
1 1 2 2 4
2 1 3 2 6
將DataFrame.mul
與MultiIndex.from_product
和DataFrame.reindex
一起使用:
mux = pd.MultiIndex.from_product([mat1.columns, mat2.columns])
df = mat1.reindex(mux, axis=1, level=0).mul(mat2.reindex(mux, axis=1, level=1))
df.columns=[f'{a}{b}' for a, b in df.columns]
print (df)
ac ad bc bd
0 1 1 2 2
1 1 2 2 4
2 1 3 2 6
pd.concat((mat2.mul(mat1[c], axis=0).add_prefix(c) for c in mat1), axis=1)
ac ad bc bd
0 1 1 2 2
1 1 2 2 4
2 1 3 2 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.