我想找出哪封信在某一天占總價格的 50% 或更多。例如,在下面的資料集中,A 在 06/21 出現的頻率最高,但是根據價格,它不占 50% 或更多的時間。在 06/21 加起來時,A = 56(總數的 25%),B = 120(總數的 54%),C = 48(總數的 21%)。因此,對于每個日期,如果一封信占總價格的 50% 或更多,我需要輸出來顯示出現的信件以及日期。如果沒有字母具有 50% 或更多的日期,則沒有輸出。06/22 也會發生同樣的情況。盡管B出現的頻率最高,但這不是我感興趣的。B占當天總價格的59%,而A是5%,C是35%。所以輸出將是:
B 06/21 0.54 和 B 06/21 0.59
import pandas as pd
# initialise data of lists.
data = {'Name':['A', 'B', 'A', 'C', 'C', 'A', 'B', 'A', 'B','B','B', 'C', 'C'], 'Date':
['06/21', '06/21', '06/21', '06/21', '06/21', '06/21', '06/21', '06/22' , '06/22', '06/22', '06/22', '06/22', '06/22'], 'Price': [10, 27, 8, 10, 38, 38, 93, 12, 55, 39, 52, 62, 25]}
# Create DataFrame
df = pd.DataFrame(data)
# Print the output.
print(df)
uj5u.com熱心網友回復:
這可能有效:
# aggregate multiple entries on a given date
agg_by_date_name = (df
.groupby(["Date", "Name"])
.agg({"Price": "sum"})
)
# calculate share
date_sums = agg_by_date_name.groupby(["Date"])["Price"].transform("sum")
agg_by_date_name["share"] = agg_by_date_name["Price"] / date_sums
# select rows where the share is higher than 50%
keep_high_share = agg_by_date_name["share"] > 0.5
# store the result
result = agg_by_date_name.loc[keep_high_share, ["share"]]
print(result)
# share
# Date Name
# 06/21 B 0.535714
# 06/22 B 0.595918
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/402818.html
標籤:
