首頁 >後端開發 >Python教學 >如何計算 Pandas DataFrame 中每個叢集中每個組織的平均時間?

如何計算 Pandas DataFrame 中每個叢集中每個組織的平均時間?

Susan Sarandon
Susan Sarandon原創
2024-11-14 20:49:02408瀏覽

How to Calculate the Average Time per Organization Within Each Cluster in a Pandas DataFrame?

執行分組聚合和平均計算

考慮以下帶有叢集、組織和時間資料的DataFrame:

  cluster org  time
0       a    8
1       a    6
2       h   34
3       c   23
4       d   74
5       w    6

目標是計算每個集群中每個組織的平均時間。預期結果應類似於:

cluster  mean(time)
1        15 #=((8 + 6) / 2 + 23) / 2
2        54 #=(74 + 34) / 2
3        6

使用雙重GroupBy 和平均值計算的解決方案:

要實現此目的,請利用Pandas 的groupby 函數的強大功能:

  1. 初始GroupBy:使用groupby(['cluster', 'org']) 依'cluster' 和'org' 將資料分組。
  2. Intermediate Aggregate:使用mean()計算每組內的時間平均值。
  3. Secondary GroupBy:使用groupby('cluster'按'cluster'進一步對產生的DataFrame進行分組).
  4. 最終聚合:使用🎜>
最終聚合
cluster_org_time = df.groupby(['cluster', 'org'], as_index=False).mean()
result = cluster_org_time.groupby('cluster')['time'].mean()
:使用mean()計算每個群集的時間平均值。

集群組的替代解決方案平均值:

cluster_mean_time = df.groupby(['cluster']).mean()

僅對於聚類組的平均值,只需按['cluster' ] 分組並使用Mean() 計算平均值。

其他選項對於有org 和平均值計算的GroupBy:

cluster_org_mean_time = df.groupby(['cluster', 'org']).mean()
或者,您可以按['cluster', 'org'] 分組並直接計算平均值:

以上是如何計算 Pandas DataFrame 中每個叢集中每個組織的平均時間?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn