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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:55:40  来源:igfitidea点击:

create matrix structure using pandas

pythonpandasnumpydataframe

提问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.multiplybut I am not successful in producing the result.

我正在使用np.multiply但我没有成功产生结果。

采纳答案by piRSquared

numpy as a faster alternative

numpy 作为更快的选择

pd.DataFrame(np.outer(df, df), df.index, df.index)

enter image description here

在此处输入图片说明



Timing

定时

Given sample

给定样本

enter image description here

在此处输入图片说明

30,000 rows

30,000 行

df = pd.concat([df for _ in range(10000)], ignore_index=True)

enter image description here

在此处输入图片说明

回答by Boud

You want to do the math between a vector and its tranposition. Transpose with .Tand apply the matrix dotfunction 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