第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

帶過濾器的聚合數(shù)據(jù)框

帶過濾器的聚合數(shù)據(jù)框

UYOU 2023-09-05 21:13:36
pandas 是否可以使用“NamedAgg”方法進行過濾?這是我的示例代碼:df = pd.DataFrame({'Person': ['John','Paul','John','Paul','Taylor'],                   'animal': ['cat', 'dog', 'cat', 'dog','dog'],                   'from' : ['breeder','adoption','adoption','breeder','wild'],                   'height': [9.1, 6.0, 9.5, 34.0,55],                   'weight': [7.9, 7.5, 9.9, 198.0,200]})df.groupby(['Person']).agg(    number_of_animal = pd.NamedAgg(column = 'animal', aggfunc = 'count'),    number_of_from = pd.NamedAgg(column = 'from', aggfunc = 'count'),    total_height = pd.NamedAgg(column = 'height', aggfunc = 'sum'),    total_weight = pd.NamedAgg(column = 'weight', aggfunc = 'sum')    )result = pd.DataFrame({'Person': ['John','Paul','Taylor'],                        'number_of_animal':[2,0,0],                        'number_of_from': [1,1,0],                        'total_height':[0,34,55],                        'total_weight':[17.8,205.5,200]})對于每個單獨的列,我想應(yīng)用一個過濾器,例如我想過濾“number_of_animal”df['animal'] == 'cat'和“total_hight”df['height'] > 10和 number_of_fromdf['from'] == 'breeder
查看完整描述

1 回答

?
一只名叫tom的貓

TA貢獻1906條經(jīng)驗 獲得超3個贊

使用DataFrame.assignfor reasign 將不匹配的值替換為NaN中的 s?Series.where

df1 = (df.assign(animal = df['animal'].where(df['animal'] == 'cat'),

? ? ? ? ? ? ? ? ?height = df['height'].where(df['height'] > 10),

? ? ? ? ? ? ? ? ?from1 = df['from'].where(df['from'] == 'breeder')

? ? ? ? ? ? ? ? )

? ? ? ? .groupby(['Person']).agg(

? ? ? ? ? ? ? ? ?number_of_animal = pd.NamedAgg(column = 'animal', aggfunc = 'count'),

? ? ? ? ? ? ? ? ?number_of_from = pd.NamedAgg(column = 'from1', aggfunc = 'count'),

? ? ? ? ? ? ? ? ?total_height = pd.NamedAgg(column = 'height', aggfunc = 'sum'),

? ? ? ? ? ? ? ? ?total_weight = pd.NamedAgg(column = 'weight', aggfunc = 'sum')

? ? ))

print (df1)

? ? ? ? number_of_animal? number_of_from? total_height? total_weight

Person? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

John? ? ? ? ? ? ? ? ? ?2? ? ? ? ? ? ? ?1? ? ? ? ? ?0.0? ? ? ? ? 17.8

Paul? ? ? ? ? ? ? ? ? ?0? ? ? ? ? ? ? ?1? ? ? ? ? 34.0? ? ? ? ?205.5

Taylor? ? ? ? ? ? ? ? ?0? ? ? ? ? ? ? ?0? ? ? ? ? 55.0? ? ? ? ?200.0


查看完整回答
反對 回復(fù) 2023-09-05
  • 1 回答
  • 0 關(guān)注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號