简体   繁体   English

基于其他 dataframe 索引在特定级别上重新索引 Multiindex dataframe

[英]Reindex Multiindex dataframe on a specific level based on other dataframe index

I have a Multiindex dataframe [id, currency] as an input.我有一个 Multiindex dataframe [id, currency] 作为输入。 I want it to be filtered by the price dataframe index on the level currency.我希望它被水平货币上的price dataframe 指数过滤。 Any contribution would be appreciated.任何贡献将不胜感激。

balance dataframe: balance dataframe:

                balance
id   currency   
1    JPY        2322
     USD        w3r234
     KWN        23423
2    POPO       234234 
     USDC       3w4234
     BTC         54545
     ETH         2323412

price dataframe: price dataframe:

JPY        0.3
KWN        0.5
POPO       0.2 
USDC       0.5
ETH        0.3

Desired output is the scaled balance dataframe:所需的 output 是比例balance dataframe:

                balance
id   currency   
1    JPY        2322
     KWN        23423
2    POPO       234234 
     USDC       3w4234
     ETH         2323412

My code:我的代码:

idx = price.index
balance = balance.reindex(idx, level='currency', fill_value=0).sort_index()

Access the values of the desired level and filter based on the items present in price dataframe:访问所需级别的值并根据price dataframe 中存在的项目进行过滤:

df = balance[np.in1d(balance.index.get_level_values(1), price.index)]

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

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