背景 -
我有一個 Pandas DataFrame,其中包含我想對其進行一些計算的資料。具體來說,我需要遍歷 DataFrame 的每一行并計算一個計算,如果在 Excel 中,它將是=SUMIF.
計算 ( =SUMIFS([% Ownership],[Entity ID],[@[Entity ID]])) -
在此計算中,采用Entity ID列中的整數值,并且對于整個 DataFrame中Entity ID位于列中的整數值的每個實體Entity ID,其對應的% Ownership值被求和并列印在Entity ID % Column.
>>> df
Entity ID % Ownership Entity ID %
0 12345 100.00 1.000000
1 45643 49.56 0.495551
2 00000 100.00 2.000000
3 00000 100.00 2.000000
在上面的例子中:
12345在 DataFrame 中只出現一次,因此它的Entity ID值為 1.000000。45643僅在 DataFrame 中出現一次(值為 49.56),因此其Entity ID值為 0.495551。00000在 DataFrame 中出現兩次(兩個實體都具有 1.0 值),因此其Entity ID值為 2.000000。
有用的資訊:
- 您會注意到
% Ownership和Entity ID %列中的資料格式不同(例如,100.00 與 1.00000),這就是我的 Excel 作業簿中單元格的格式,如果可能,我希望使用這種格式和小數四舍五入。 - 我想了解如何遍歷我的 DataFrame 中的每一行(它是 4000 行)并使用 for 回圈執行這樣的計算,以便有效地對每一行執行此計算。
uj5u.com熱心網友回復:
我們可以使用 agroupby將總和和assign結果直接放入 DataFrame 中,如下所示:
>>> df.assign(Entity_ID_perc = df.groupby('Entity ID')['% Ownership'].sum() / 100)
Entity ID % Ownership Entity_ID_perc
0 12345 100.00 1.0000
1 45643 49.56 0.4956
2 00000 100.00 2.0000
3 00000 100.00 2.0000
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/378579.html
