Pandas 按自定义函数分组

Pandas group by custom function

这应该很简单。我想要的是按函数结果分组的能力,就像在 SQL 中你可以按表达式分组:

SELECT substr(name, 1) as letter, COUNT(*) as count
FROM table
GROUP BY substr(name, 1)

这将计算名称列以字母表中的每个字母开头的行数。

我想在 python 中做同样的事情,所以我假设我可以将一个函数传递给 groupby。但是,这只会将索引列(第一列)传递给函数,例如 0、1 或 2。我想要的是名称列:

import pandas

# Return the first letter
def first_letter(row):

    # row is 0, then 1, then 2 etc.
    return row.name[0]

#Generate a data set of words
test = pandas.DataFrame({'name': ["benevolent", "hidden", "absurdity", "anonymous", "furious", "antidemocratic", "honeydew"]})

#              name
# 0      benevolent
# 1          hidden
# 2       absurdity
# 3       anonymous
# 4         furious
# 5  antidemocratic
# 6        honeydew

test.groupby(first_letter)

我在这里做错了什么。怎么能按行索引以外的东西分组?

为第一个字母创建一个新列:

def first_letter(row):
    return row[0]

test['first'] = test['name'].apply(first_letter)

并将其分组:

group = test.groupby('first')

使用它:

>>> group.count()

     name
first      
a         3
b         1
f         1
h         2

您通常希望在字符串列上使用矢量化 str 运算符。使用 get(0) 提取第一个字母,然后在 groupby 操作中使用。最后,我们取 count 个结果。

这是 working with text data 的 Pandas 文档的 link。

请注意,您可以使用正则表达式模式来 extract 更复杂的表达式。

>>> test.groupby(test['name'].str.get(0))['name'].count()
name
a       3
b       1
f       1
h       2
Name: name, dtype: int64

更一般地说,您的函数应该 return 数据框中的唯一项目,在这些项目上隐式分组与其索引。

例如,舍入数字的函数可用于对舍入后的数字进行分组。

df = pd.DataFrame({'A': [0.25, 0.75, 2.6, 2.7, 2.8]})

>>> np.round(df.A)
0    0
1    1
2    3
3    3
4    3
Name: A, dtype: float64

>>> df.groupby(np.round(df.A)).mean()
      A
A      
0  0.25
1  0.75
3  2.70

自定义函数应应用于一系列数据框,例如布尔运算符:

def ge_two(series):
    return series >= 2

>>> df.groupby(ge_two(df.A)).sum()
         A
A         
False  1.0
True   8.1