Pandas multiply dataframes with multiindex and overlapping index levels

前端 未结 3 581
情书的邮戳
情书的邮戳 2021-01-01 16:28

I´m struggling with a task that should be simple, but it is not working as I thought it would. I have two numeric dataframes A and B with multiindex and columns below:

3条回答
  •  时光取名叫无心
    2021-01-01 17:32

    Note that I am not claiming this is the right way to do this operation, only that it's one way to do it. I've had issues figuring out the right broadcast pattern in the past myself. :-/

    The short version is that I wind up doing the broadcasting manually, and creating an appropriately-aligned intermediate object:

    In [145]: R = B * A.loc[B.index.droplevel(2)].set_index(B.index)
    
    In [146]: A.loc[("X", 2), "C"]
    Out[146]: 0.5294149302910357
    
    In [147]: A.loc[("X", 2), "C"] * B.loc[("X", 2, "c"), "C"]
    Out[147]: 0.054262618238601339
    
    In [148]: R.loc[("X", 2, "c"), "C"]
    Out[148]: 0.054262618238601339
    

    This works by indexing into A using the matching parts of B, and then setting the index to match. If I were more clever I'd be able to figure out a native way to get this to work but I haven't yet. :-(

提交回复
热议问题