简体   繁体   English

如何获得具有匹配索引的数据框中行的标量积

[英]How to get a scalar product of rows in dataframe with matching indexes

Let's say I have two dataframes with same columns, first one has unique index, second has not unique index,假设我有两个具有相同列的数据框,第一个具有唯一索引,第二个没有唯一索引,

      column1  column2
a        1       2
b        4       5
c        3       3

      column1  column2
a        1       2
a        4       5
c        3       3
b        1       2
b        4       5
a        3       3

Now how can I make a scalar product of rows where index match, the result would be a dataframe with one column (with values of scalar product, for example first row: 1*1+2*2=5 ) and index as in second dataframe:现在我如何制作索引匹配的行的标量积,结果将是一个具有一列的数据帧(具有标量积的值,例如第一行: 1*1+2*2=5 )和第二个中的索引数据框:

      result
a        5  
a        14 
c        18  
b        14 
b        41  
a        9  

Multiple and then sum DataFrame s:多个然后对DataFrame求和:

df = df2.mul(df1).sum(axis=1).to_frame('result')
print (df)
   result
a       5
a      14
a       9
b      14
b      41
c      18

If ordering is important in ouput:如果排序在输出中很重要:

df = (df2.assign(a=range(len(df2)))
         .set_index('a', append=True)
         .mul(df1, level=0)
         .sum(axis=1)
         .droplevel(1)
         .to_frame('result'))
print (df)
   result
a       5
a      14
c      18
b      14
b      41
a       9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM