python - 对多索引数据帧的行求和,但在缺失数据中显示 0

标签 python python-3.x pandas dataframe multi-index

我有一个多索引数据框,想对这些值求和。如果没有行,我需要像下面的示例一样显示 0

import pandas as pd

d = {'City': ['Tokyo','Tokyo','Lisbon','Tokyo','Madrid','New York','Madrid','London','Tokyo','London','Tokyo'], 
     'Card': ['Visa','Visa','Visa','Master Card','Bitcoin','Master Card','Bitcoin','Visa','Master Card','Visa','Bitcoin'],
     'Colateral':['Yes','Yes','No','No','Yes','No','No','Yes','Yes','No','Yes'],
     'Client Number':[1,2,3,4,5,6,7,8,9,10,11],
     'Total':[100,100,200,300,10,20,40,50,60,100,500]}

df = pd.DataFrame(data=d)

df.set_index(['City','Card','Colateral']).drop(['Client Number'],axis=1)
df.sum(level=[0,1])

我希望完成的结果是这样的

enter image description here

最佳答案

使用DataFrame.reindexMultiIndex.from_product :

df1 = (df.set_index(['City','Card','Colateral'])
         .drop(['Client Number'],axis=1)
         .sum(level=[0,1,2]))


df2 = df1.reindex(pd.MultiIndex.from_product(df1.index.levels), fill_value=0)

print (df2)
         Total
City     Card        Colateral       
Lisbon   Bitcoin     No             0
                     Yes            0
         Master Card No             0
                     Yes            0
         Visa        No           200
                     Yes            0
London   Bitcoin     No             0
                     Yes            0
         Master Card No             0
                     Yes            0
         Visa        No           100
                     Yes           50
Madrid   Bitcoin     No            40
                     Yes           10
         Master Card No             0
                     Yes            0
         Visa        No             0
                     Yes            0
New York Bitcoin     No             0
                     Yes            0
         Master Card No            20
                     Yes            0
         Visa        No             0
                     Yes            0
Tokyo    Bitcoin     No             0
                     Yes          500
         Master Card No           300
                     Yes           60
         Visa        No             0
                     Yes          200

关于python - 对多索引数据帧的行求和,但在缺失数据中显示 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62637403/

相关文章:

python - Django 不必要地向日期时间添加 5 小时的问题。

python - 为什么当线程数增加到超过硬件可能的线程数时性能会提高?

python - 无需任何显式调用即可更改变量值

python - 如何选择过滤器选择列表中的列列表

python - 单词和表情符号计数器

python - 无法更新在 Google Cloud Platform 上构建的网站

Python - 在字典中查找顶部项目

python - 使用 Pandas Dataframes 根据间隙长度计算事件日期

python - 如何通过单击按钮重新执行我的 Python 程序

python - 创建一个数据框,包括分组总和和总和