日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python?groupby函數實現分組后選取最值_python

作者:Vergil_Zsh ? 更新時間: 2022-08-11 編程語言

現在需要將course分組,然后選擇出每一組里面的最大值和最小值,并保留下來

實現下面數據結果:

直接使用groupby函數,不能直接達到此效果,需要在groupby函數上添加apply和lambda函數

代碼如下:

import pandas as pd
data = pd.read_excel('group_apply.xlsx')
data1 = data.groupby('course').apply(lambda t: t[(t['grade']==t['grade'].min()) ^ (t['grade']==t['grade'].max())])

前面的index,是兩列,所以需要處理一下,這個是groypby函數處理之后所產生,只需要刪除即可

data2 = data1.reset_index(drop=True)

代碼整合:

import pandas as pd
data = pd.read_excel('group_apply.xlsx')
data1 = data.groupby('course').apply(lambda t: t[(t['grade']==t['grade'].min()) ^ (t['grade']==t['grade'].max())])
data2 = data1.reset_index(drop=True)

寫入到excel中:

原文鏈接:https://blog.csdn.net/KIKI_ZSH/article/details/124548025

欄目分類
最近更新