在 pandas 中将两个序列与MultiIndex相乘 [英] Multiply two Series with MultiIndex in pandas

查看:85
本文介绍了在 pandas 中将两个序列与MultiIndex相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将两个Series都乘以MultiIndex:

I am trying to multiply two Series, both with MultiIndex:

import pandas as pd
tuples = [(0, 100, 1000),(0, 100, 1001),(0, 100, 1002), (1, 101, 1001)]
index_3levels=pd.MultiIndex.from_tuples(tuples,names=["l1","l2","l3"])
tuples = [(0, 100), (1, 101)]
index_2levels=pd.MultiIndex.from_tuples(tuples,names=["l1","l2"])
data_3levels = pd.Series(1, index=index_3levels)
data_2levels = pd.Series([2,3], index=index_2levels)
print data_3levels  
l1  l2   l3  
0   100  1000    1
         1001    1
         1002    1
1   101  1001    1
dtype: int64
print data_2levels
l1  l2 
0   100    2
1   101    3
dtype: int64

问题是我无法将Series从2级重新索引为3级:

The problem is that I cannot reindex the Series from 2 to 3 levels:

data_2levels.reindex(data_3levels.index, level=["l1","l2"])
Exception: Join on level between two MultiIndex objects is ambiguous

我找到了解决方法:

for l1 in [0,1]:
    data_3levels[l1] *= data_2levels[l1].reindex(data_3levels[l1].index, level="l2")
print data_3levels
l1  l2   l3  
0   100  1000    2
         1001    2
         1002    2
1   101  1001    3
dtype: int64

但是我认为应该有一种方法可以仅一步完成该操作.

But I think there should be a method to perform this operation in just 1 step.

推荐答案

尝试一下. reset_index删除最后一个级别,因此乘以它们是相同的

Try this. reset_index removes the last level, so they are the same when you multiply

In [25]: x = data_3levels.reset_index(level=2,drop=True)*data_2levels

由于您想要原始索引(并且形状未更改),因此可以正常工作.

Since you want the original index (and the shape hasn't changed), this works.

In [26]: x.index=data_3levels.index

In [27]: x
Out[27]: 
l1  l2   l3  
0   100  1000    2
         1001    2
         1002    2
1   101  1001    3
dtype: int64

这篇关于在 pandas 中将两个序列与MultiIndex相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆