熊猫pivot_table应用agfunc最后一个实例

sto*_*r12 3 python pandas

我制作了具有各种列的数据透视表,并应用了aggfunc,例如np.sum和first和count。我想要数据帧中列的对应值的最后一个实例。是否有任何功能可以达到此目的?

jez*_*ael 5

我想你可以用

aggfunc='last'
Run Code Online (Sandbox Code Playgroud)

样品:

df = pd.DataFrame({ 'Age':[35, 37, 40, 29, 31, 26, 28],
                   'City':['B', 'Ch', 'LA', 'Ch', 'B', 'B', 'Ch'],
                   'Position':['M','M','M','P', 'P','M','M']})
print (df)
   Age City Position
0   35    B        M
1   37   Ch        M
2   40   LA        M
3   29   Ch        P
4   31    B        P
5   26    B        M
6   28   Ch        M

print (df.pivot_table(index='Position', columns='City', values='Age', aggfunc='last'))
City         B    Ch    LA
Position                  
M         26.0  28.0  40.0
P         31.0  29.0   NaN
Run Code Online (Sandbox Code Playgroud)