簡體   English   中英

Python Pandas - 根據要匹配到列名的另一個表的值切片 DataFrame

[英]Python Pandas - Slice DataFrame based on Another Table's Values to Match to Column Name

我有兩個數據框,df_stats 和 df_ratings。

df_stats 看起來像這樣

水果 Rating_Threshold_Low Rating_Threshold_High
1 蘋果 4 7
2 香蕉 5 9
3 獼猴桃 6 8

df_ratings 看起來像這樣(第一列是Fruit並且每個后續列代表一個rating

水果 1 2 3 4 5 6 7 8 9 10
1 蘋果 2 4 7 13 2 0 16 1 9 22
2 香蕉 6 4 2 1 8 7 5 3 9 0
3 獼猴桃 21 4 3 6 8 9 9 8 7 5

我的目標是獲得每個水果的評分閾值內的評分總數(每個水果的評分閾值不同)。 換句話說,我想在 df_stats 添加列df_stats ,它計算閾值df_ratings內的評分總和。 例如,對於Apple ,Rating 閾值介於 4 和 7(含)之間,因此Rating_Threshold_Sum將為 13+2+0+16 = 31。

因此, df_stats將具有Ratings_Threshold_Sum列:

水果 Rating_Threshold_Low Rating_Threshold_High Rating_Threshold_Sum
1 蘋果 4 7 31
2 香蕉 5 9 32
3 獼猴桃 6 8 26

我不確定該怎么做,我知道我可能必須將 df.apply 與自定義 function 一起使用,或者遍歷每一行,但除此之外,我不確定解決這個問題的最佳方法。 任何建議/方向將不勝感激。 謝謝!

你可以做這樣的事情

sums = []
for i in range(len(df_stats)):
   min_v, max_v = df_stats["Rating_Threshold_Low"].values()[i], df_stats["Rating_Threshold_High"].values()[i]  
   values = []
   for z in range(min_v, max_v+1):
      x = df_ratings[str(z)][i]
      values.append(x)
   sums.append(sum(values))
df_stats["Rating_Threshold_Sum"] = sums

這真的很復雜,可能有更好的方法來做到這一點,但它應該可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM