按行名称分组Pandas DataFrame

时间:2014-04-03 13:56:54

标签: python pandas dataframe row pandas-groupby

我有一个简单的Pandas DataFrame,其中包含行名和2列,如下所示。

from pandas import DataFrame, Series
row_names = ['row1', 'row2', 'row2', 'row4']
df = DataFrame({'col1': Series([1, 2, 3, 4], index=row_names),
                'col2': Series([0, 1, 0, 1], index=row_names)})

与上面的示例一样,某些行名称会重复。我想按行名对DataFrame进行分组,以便我可以按组执行聚合操作(例如,count,mean)。

例如,我可能想知道row1row4df中出现row2groupby出现一次。

我知道{{1}}方法,但从我在网上看过的例子中,它只按列值分组,而不是按行名称分组。是这样的吗?我应该将我的rownames作为DataFrame中的列吗?

1 个答案:

答案 0 :(得分:1)

检查文档字符串(如果您正在使用IPython,它只是df.groupby?<enter>

Group series using mapper (dict or key function, apply given function
to group, return result as series) or by a series of columns

Parameters
----------
by : mapping function / list of functions, dict, Series, or tuple /
    list of column names.
    Called on each element of the object index to determine the groups.
    If a dict or Series is passed, the Series or dict VALUES will be
    used to determine the groups
axis : int, default 0
level : int, level name, or sequence of such, default None
    If the axis is a MultiIndex (hierarchical), group by a particular
    level or levels
...

您需要level参数:

In [20]: df.groupby(level=0).count()
Out[20]: 
      col1  col2
row1     1     1
row2     2     2
row4     1     1

[3 rows x 2 columns]