以下是一个示例代码,展示了如何按最大值分组而不丢弃列:
import pandas as pd
# 创建示例数据框
data = {'Group': ['A', 'A', 'B', 'B', 'C', 'C'],
'Value': [1, 2, 3, 4, 5, 6],
'OtherColumn': ['X', 'Y', 'Z', 'W', 'P', 'Q']}
df = pd.DataFrame(data)
# 按 Group 列进行分组,获取每组的最大值所在的行
max_rows = df.groupby('Group')['Value'].idxmax()
# 根据得到的索引获取最大值所在的行,并保留其他列
result = df.loc[max_rows]
print(result)
输出结果为:
Group Value OtherColumn
1 A 2 Y
3 B 4 W
5 C 6 Q
在上面的示例中,我们首先创建了一个包含 Group、Value 和 OtherColumn 列的示例数据框。然后,我们使用 Pandas 的 groupby()
函数按 Group 列进行分组,并使用 idxmax()
方法获取每组的最大值所在的行的索引。最后,使用 loc[]
方法根据得到的索引获取最大值所在的行,并保留其他列。