简体   繁体   中英

pandas: Multiply MultiIndex DataFrame with Series

I have a MultiIndex DataFrame that contains these values:

                      AAPL
           minor          
2007-09-14 OC     0.024436
2007-09-15 CC     0.030293
           CO     0.017518
           OC     0.024688
           OO     0.031835

# to_dict():

{'AAPL': {(<Timestamp: 2007-09-14 00:00:00>, 'OC'): 0.024436265475779286,
  (<Timestamp: 2007-09-15 00:00:00>, 'CC'): 0.030293017084353703,
  (<Timestamp: 2007-09-15 00:00:00>, 'CO'): 0.017518449703066673,
  (<Timestamp: 2007-09-15 00:00:00>, 'OC'): 0.024688182799779634,
  (<Timestamp: 2007-09-15 00:00:00>, 'OO'): 0.031834725061579666}}

--

and a Series that contains these values:

CC    15.874508
CO    18.590320
OC    30.503468
OO    15.874508

# to_dict():

{'CC': 15.874507866387544,
 'CO': 18.590320061795602,
 'OC': 30.503467646507644,
 'OO': 15.874507866387544}

I'd like to multiply all of the minor index CC values by the CC value in the Series, and the same with the other values. I saw another question on here that gave me the .mul method, but when I try that, even with the level='minor', it tells me:

TypeError: can only call with other hierarchical index objects

I've unstacked the minor index to make it columns, and specified level='minor', axis='columns' with the same result.

Finally, the end result is to be able to run this same calculation on a DataFrame where the major columns are several equities -- in that instance, would .mul() work against each equity as well?

Thanks for your assistance!

Series based it works with level :

df["C01"].mul(s, level=1)

major       minor
2007-09-14  OC       0.745391
2007-09-15  CC       0.480887
            CO       0.325674
            OC       0.753075
            OO       0.505361

Then you can insert it again into your DataFrame. But that should work with DataFrames too, maybe you can suggest it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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