要按照特定的公式对pandas进行分组,可以使用groupby
函数结合自定义的公式来实现。以下是一个示例代码:
import pandas as pd
# 创建示例数据
data = {'Name': ['Tom', 'Nick', 'John', 'Tom', 'John'],
'Age': [20, 21, 22, 20, 22],
'Height': [165, 170, 175, 165, 175]}
df = pd.DataFrame(data)
# 定义分组公式
def group_formula(x):
return (x['Age'] // 10) * 10
# 按照公式分组
grouped = df.groupby(group_formula)
# 打印每个分组的统计摘要
for name, group in grouped:
print(f"Group: {name}")
print(group)
print()
输出结果:
Group: 20
Name Age Height
0 Tom 20 165
3 Tom 20 165
Group: 21
Name Age Height
1 Nick 21 170
Group: 22
Name Age Height
2 John 22 175
4 John 22 175
在示例中,我们创建了一个包含姓名、年龄和身高的DataFrame。然后,我们定义了一个名为group_formula
的函数,该函数根据年龄的十位数进行分组。使用groupby
函数,并将group_formula
函数作为参数传递给groupby
函数,我们将DataFrame按照指定的公式进行分组。最后,我们遍历每个分组,并打印每个分组的统计摘要。