How to select columns from groupby object in pandas?

前端 未结 4 1963
甜味超标
甜味超标 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:22

    You can also reset_index() on your groupby result to get back a dataframe with the name column now accessible.

    import pandas as pd
    df = pd.DataFrame({"a":[1,1,3], "b":[4,5.5,6], "c":[7,8,9], "name":["hello","hello","foo"]})
    df_grouped = df.groupby(["a", "name"]).median().reset_index()
    df_grouped.name
     0    hello
     1      foo
     Name: name, dtype: object
    

    If you perform an operation on a single column the return will be a series with multiindex and you can simply apply pd.DataFrame to it and then reset_index.

提交回复
热议问题