亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

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

將自定義函數傳遞給 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()對于file_size我想使用以下計算:sum([item['file_size'] for item in df if item['is_main_video'] is True])我將如何在 內執行上述操作.agg()?
查看完整描述

2 回答

?
慕桂英546537

TA貢獻1848條經驗 獲得超10個贊

agg在您的情況下,將標記一列作為源,您可以在之前創建另一列groupby


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()


查看完整回答
反對 回復 2023-12-08
?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

您可以Series.where暫時“忽略”您的 file_sizes,其中“is_main_video”為 False,然后執行 groupby 操作來對剩余內容進行求和:


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


查看完整回答
反對 回復 2023-12-08
  • 2 回答
  • 0 關注
  • 196 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號