python - 具有多索引的 Pandas 分区 (.div)

标签 python pandas

我有类似的东西

df = pd.DataFrame(np.random.randint(2, 10, size = (5, 2)))
df.index = pd.MultiIndex.from_tuples([(1, 'A'), (2, 'A'), (4, 'B'), 
           (5, 'B'), (8, 'B')])
df.index.names = ['foo', 'bar']
df.columns = ['count1', 'count2']
df

给出:

       count1 count2
foo bar     
1   A    6     7
2   A    2     9
4   B    6     7
5   B    4     6
8   B    5     6

我还有一个总计列表 - 从其他地方获得 - 通过相同的 'foo' 索引:

totals = pd.DataFrame([2., 1., 1., 1., 10.])
totals.index = [1, 2, 4, 5, 8]
totals.index.names = ['foo']
totals

给出:

     0
foo 
1    2
2    1
4    1
5    1
8    10

如何将 df 的所有列(count1count2)除以 totals 中的 foo 数? (因此,我需要匹配“foo”号)

我检查了this question ,看起来应该可以解决问题,但我想不通。

我试过了

df.div(totals, axis = 0)

并更改 div 中的 level 选项,但没有成功。

一如既往,非常感谢您的宝贵时间

最佳答案

尝试:

df.div(totals[0],axis='index',level='foo')

         count1  count2
foo bar                
1   A       1.0     4.5
2   A       4.0     8.0
4   B       5.0     9.0
5   B       5.0     5.0
8   B       0.9     0.5

还有:

totals = pd.DataFrame([2., 1., 1., 1., 10.])
totals.index = [[1, 2, 4, 5, 8],['A', 'A', 'B', 'A', 'B']]
totals.index.names = ['foo','bar']
totals
           0
foo bar      
1   A     2.0
2   A     1.0
4   B     1.0
5   A     1.0
8   B    10.0

df[['count1','count2']].div(totals[0],axis='index')
         count1  count2
foo bar                
1   A       1.0     4.5
2   A       4.0     8.0
4   B       5.0     9.0
5   A       NaN     NaN
    B       NaN     NaN
8   B       0.9     0.5

关于python - 具有多索引的 Pandas 分区 (.div),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19523370/

相关文章:

python - 使用 python 的 os.walk 来搜索特定的目录名称?

python - 基于最左索引对多索引数据框中的列应用相关数学运算

python - 派生类不调用 init

python - 如何在 Python 应用程序中建立与 Kerberos 的连接?

python - 将元组列表映射到新列

python - 根据 pandas 中的另一个列值突出显示一个列值

python - 按 Pandas 中的第二个项目对元组系列进行排序

python-3.x - 按行特定列表选择 Pandas 数据框列

python - 如何理解 Peter Norvig 的这段 Python 函数式代码?

python - 通过 Pipenv 使用 .env 文件修改 PYTHONPATH