gpt4 book ai didi

python - Pandas 按自定义功能分组

转载 作者:太空宇宙 更新时间:2023-11-03 12:57:49 25 4
gpt4 key购买 nike

这应该很简单。我想要的是按函数结果分组的能力,就像在 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

关于python - Pandas 按自定义功能分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34169322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com