【问题标题】:How do I delete rows which have only one entry in multi-index dataframe?如何删除多索引数据框中只有一个条目的行?
【发布时间】:2019-11-02 03:07:22
【问题描述】:

我有以下类型的多索引数据框:


import random
col3=[0,0,0,0,2,4,6,0,0,0,100,200,300,400]
col4=[0,0,0,0,4,6,8,0,0,0,200,900,400, 500]

d = {'Unit': [1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 6, 6, 6, 6], 
 'Year': [2014, 2015, 2016, 2017, 2015, 2016, 2017, 2017, 2014, 2015, 2014, 2015, 2016, 2017], 'col3' : col3, 'col4' : col4 }
df = pd.DataFrame(data=d)
new_df = df.groupby(['Unit', 'Year']).sum()

           col3  col4     
Unit Year                      
1    2014     0     0      
     2015     0     0       
     2016     0     0      
     2017     0     0      
2    2015     2     4       
     2016     4     6  
     2017     6     8  
3    2017     0     0    
4    2014     0     0      
5    2015     0     0      
6    2014   100   200       
     2015   200   900  
     2016   300   400  
     2017   400   500  

实际上它当然更大,但这确实有效。在这个数据框中,我想删除所有只有一年条目的单位。所以我想要这个:

           col3  col4     
Unit Year                      
1    2014     0     0      
     2015     0     0       
     2016     0     0      
     2017     0     0      
2    2015     2     4       
     2016     4     6  
     2017     6     8         
6    2014   100   200       
     2015   200   900  
     2016   300   400  
     2017   400   500  

提前感谢您的帮助,

【问题讨论】:

  • 谢谢你,这确实是一个错误。也应该删除,我编辑!

标签: python pandas pandas-groupby multi-index


【解决方案1】:

GroupBy.transform 用于任何列,并使用GroupBy.size 测试计数,使用Series.ne 比较不等于并使用boolean indexing 过滤:

df = new_df[new_df.groupby(level=0)['col3'].transform('size').ne(1)]

或者通过Index.get_level_values获取索引值并通过Index.duplicated过滤:

df = new_df[new_df.index.get_level_values(0).duplicated(keep=False)]

print (df)
           col3  col4
Unit Year            
1    2014     0     0
     2015     0     0
     2016     0     0
     2017     0     0
2    2015     2     4
     2016     4     6
     2017     6     8
6    2014   100   200
     2015   200   900
     2016   300   400
     2017   400   500

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    相关资源
    最近更新 更多