gpt4 book ai didi

python - Pandas 按应用于列的功能分组

转载 作者:太空宇宙 更新时间:2023-11-03 13:08:47 32 4
gpt4 key购买 nike

在 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))

最佳答案

来自 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``

所以我们可以这样做:

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

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

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