0

次のような、行名と 2 つの列を持つ単純な Pandas DataFrame があります。

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 をグループ化して、グループ (カウント、平均など) ごとに集計操作を実行できるようにします。

たとえば、私はそれを見つけて、my にそれぞれ 1 回ずつ現れたいrow1と思うかもしれません。row4dfrow2

私はそのgroupby方法を知っていますが、オンラインで見た例では、行名ではなく、列の値でグループ化するだけです。そうですか?行名をデータフレームの列にするだけですか?

4

1 に答える 1

2

docstring を確認します ( 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]
于 2014-04-03T14:57:57.877 に答える