pandas 使用熊猫创建矩阵结构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39240286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
create matrix structure using pandas
提问by dataviz
I have loaded the below CSV file containing code and coefficient data into the below dataframe df:
我已将包含代码和系数数据的以下 CSV 文件加载到以下数据框 df 中:
CODE|COEFFICIENT
A|0.5
B|0.4
C|0.3
import pandas as pd
import numpy as np
df= pd.read_csv('cod_coeff.csv', delimiter='|', encoding="utf-8-sig")
giving
给予
ITEM COEFFICIENT
0 A 0.5
1 B 0.4
2 C 0.3
From the above dataframe, I need to create a final dataframe as below which has a matrix structure with the product of the coefficients:
从上面的数据帧中,我需要创建一个最终的数据帧,如下所示,它具有矩阵结构和系数的乘积:
A B C
A 0.25 0.2 0.15
B 0.2 0.16 0.12
C 0.15 0.12 0.09
I am using np.multiply
but I am not successful in producing the result.
我正在使用np.multiply
但我没有成功产生结果。
采纳答案by piRSquared
回答by Boud
You want to do the math between a vector and its tranposition. Transpose with .T
and apply the matrix dot
function between the two dataframes.
您想在向量与其换位之间进行数学运算。在两个数据帧之间转置.T
并应用矩阵dot
函数。
df = df.set_index('CODE')
df.T
Out[10]:
CODE A B C
COEFFICIENT 0.5 0.4 0.3
df.dot(df.T)
Out[11]:
CODE A B C
CODE
A 0.25 0.20 0.15
B 0.20 0.16 0.12
C 0.15 0.12 0.09