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

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

將自定義函數(shù)傳遞給 pandas .agg()

將自定義函數(shù)傳遞給 pandas .agg()

阿晨1998 2023-12-08 17:05:16
我在 pandas 中有以下聚合:summary_df = df.groupby(['provider', 'id']).agg(    title           =('title', 'first'),    file_size       = *custom*).reset_index()對(duì)于file_size我想使用以下計(jì)算:sum([item['file_size'] for item in df if item['is_main_video'] is True])我將如何在 內(nèi)執(zhí)行上述操作.agg()?
查看完整描述

2 回答

?
慕桂英546537

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超10個(gè)贊

agg在您的情況下,將標(biāo)記一列作為源,您可以在之前創(chuàng)建另一列g(shù)roupby


df['New'] = np.where(df['is_main_video'], df['file_size'], 0)

summary_df = df.groupby(['provider', 'id']).agg(

    title           =('title', 'first'),

    file_size       = ('New', 'sum')

).reset_index()

更新


summary_df = df.assign(New = np.where(df['is_main_video'], df['file_size'], 0)).groupby(['provider', 'id']).agg(

    title           =('title', 'first'),

    file_size       = ('New', 'sum')

).reset_index()


查看完整回答
反對(duì) 回復(fù) 2023-12-08
?
猛跑小豬

TA貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個(gè)贊

您可以Series.where暫時(shí)“忽略”您的 file_sizes,其中“is_main_video”為 False,然后執(zhí)行 groupby 操作來(lái)對(duì)剩余內(nèi)容進(jìn)行求和:


import pandas as pd


df = pd.DataFrame({

    "provider": ["A", "A", "A", "B", "B"],

    "title": ["hello", "world", "pandas", "example", "here"],

    "is_main_video": [True, False, True, True, False],

    "file_size": [10, 12, 20, 19, 10]

})


print(df)

  provider    title  is_main_video  file_size

0        A    hello           True         10

1        A    world          False         12

2        A   pandas           True         20

3        B  example           True         19

4        B     here          False         10

aggregated_df = (df.assign(file_size=df["file_size"].where(df["is_main_video"]))

                 .groupby("provider", as_index=False)

                 .agg(

                     title=("title", "first"),

                     file_size=("file_size", "sum"))

                )


print(aggregated_df)

  provider    title  file_size

0        A    hello       30.0

1        B  example       19.0


查看完整回答
反對(duì) 回復(fù) 2023-12-08
  • 2 回答
  • 0 關(guān)注
  • 192 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

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