What is as_index in groupby in pandas?

后端 未结 2 1087
走了就别回头了
走了就别回头了 2020-12-01 04:09

What exactly is the function of as_index in groupby in Pandas?

2条回答
  •  余生分开走
    2020-12-01 04:13

    When using the group by function, as_index can be set to true or false depending on if you want the column by which you grouped to be the index of the output.

    import pandas as pd
    table_r = pd.DataFrame({
        'colors': ['orange', 'red', 'orange', 'red'],
        'price': [1000, 2000, 3000, 4000],
        'quantity': [500, 3000, 3000, 4000],
    })
    new_group = table_r.groupby('colors',as_index=True).count().sort('price', ascending=False)
    print new_group
    

    output:

            price  quantity
    colors                 
    orange      2         2
    red         2         2
    

    Now with as_index=False

       colors  price  quantity
    0  orange      2         2
    1     red      2         2
    

    Note how colors is no longer an index when we change as_index=False

提交回复
热议问题