How to select columns from groupby object in pandas?

前端 未结 4 2021
甜味超标
甜味超标 2021-02-04 00:01

I grouped my dataframe by the two columns below

df = pd.DataFrame({\'a\': [1, 1, 3],
                   \'b\': [4.0, 5.5, 6.0],
                   \'c\': [7L, 8L         


        
4条回答
  •  不要未来只要你来
    2021-02-04 00:12

    You need to get the index values, they are not columns. In this case level 1

    df.groupby(["a", "name"]).median().index.get_level_values(1)
    
    Out[2]:
    
    Index([u'hello', u'foo'], dtype=object)
    

    You can also pass the index name

    df.groupby(["a", "name"]).median().index.get_level_values('name')
    

    as this will be more intuitive than passing integer values.

    You can convert the index values to a list by calling tolist()

    df.groupby(["a", "name"]).median().index.get_level_values(1).tolist()
    
    Out[5]:
    
    ['hello', 'foo']
    

提交回复
热议问题