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