【问题标题】:Matrix Multiplication of a Pandas DataFrame and SeriesPandas DataFrame 和系列的矩阵乘法
【发布时间】:2013-03-04 13:17:43
【问题描述】:

我想做一个熊猫数据框和一个系列的矩阵乘法

df = pandas.DataFrame({'a':[4,1,3], 'b':[5,2,4]},index=[1,2,3])
ser = pandas.Series([0.6,0.4])

df 是,

 a  b
1  4  5
2  1  2
3  3  4

ser 是,

0    0.6
1    0.4

我想要的结果是矩阵乘积,就像这样

是,

我可以通过使用 numpy 点运算符并重建我的数据帧来做到这一点

c = a.values.dot(b.transpose())
c = pandas.DataFrame(c, index = a.index, columns = ['ans'])
print c


   ans
1  4.4
2  1.4
3  3.4

pandas 中是否有本地方法可以做到这一点?

【问题讨论】:

    标签: python pandas matrix matrix-multiplication dot-product


    【解决方案1】:

    pandas 隐式对齐系列的索引,使用点函数

    In [3]: df = pd.DataFrame({'a' : [4,1,3], 'b' : [5,2,4]},index=[1,2,3])
    
    In [4]: s = pd.Series([0.6,0.4],index=['a','b'])
    
    In [5]: df.dot(s)
    Out[5]: 
    1    4.4
    2    1.4
    3    3.4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      相关资源
      最近更新 更多