pandas group by 函数应用于列

dle*_*eal 6 python group-by pandas

在 Groupby 文档中,我只看到了按应用于轴 0 索引或列标签的函数进行分组的示例。我没有看到讨论如何通过将函数应用于列而派生的标签进行分组的示例。我认为这将使用apply. 下面的例子是最好的方法吗?

df = pd.DataFrame({'name' : np.random.choice(['a','b','c','d','e'], 20), 
               'num1': np.random.randint(low = 30, high=100, size=20),
               'num2': np.random.randint(low = -3, high=9, size=20)})

df.head()

  name  num1 num2
0   d   34  7
1   b   49  6
2   a   51  -1
3   d   79  8
4   e   72  5

def num1_greater_than_60(number_num1):
    if number_num1 >= 60:
        return 'greater'
    else:
        return 'less'

df.groupby(df['num1'].apply(num1_greater_than_60))
Run Code Online (Sandbox Code Playgroud)

Max*_*axU 5

来自 DataFrame.groupby() 文档:

by : mapping, function, str, or iterable
    Used to determine the groups for the groupby.
    If ``by`` is a function, it's called on each value of the object's
    index. If a dict or Series is passed, the Series or dict VALUES
    will be used to determine the groups (the Series' values are first
    aligned; see ``.align()`` method). If an ndarray is passed, the
    values are used as-is determine the groups. A str or list of strs
    may be passed to group by the columns in ``self``
Run Code Online (Sandbox Code Playgroud)

所以我们可以这样做:

In [35]: df.set_index('num1').groupby(num1_greater_than_60)[['name']].count()
Out[35]:
         name
greater    15
less        5
Run Code Online (Sandbox Code Playgroud)


WeN*_*Ben 2

您可以不在这里申请

df.groupby(df.num1.gt(60))

df.num1.gt(60)
Out[774]: 
0      True
1      True
2      True
3      True
4     False
5      True
6      True
7      True
8     False
9      True
10    False
11     True
12     True
13     True
14    False
15     True
16    False
17    False
18     True
19    False
Name: num1, dtype: bool
Run Code Online (Sandbox Code Playgroud)