簡體   English   中英

使用 Python pandas 執行索引匹配

[英]Performing an index match with Python pandas

我正在努力編寫一些代碼來獲得以下功能:

df1

Date          A      B
01/01/2021    39     100
01/02/2021    58     188
01/03/2021    220    300
01/04/2021    0      11

df2

Date          A      A      A      B     B     B
              0      50     100    0     100   200
01/01/2021    0.1    0.2    0.3    0.3   0.3   0.6
01/02/2021    0.1    0.2    0.3    0.3   0.3   0.6
01/03/2021    0.3    0.3    0.6    0.5   0.4   0.8
01/04/2021    0.3    0.3    0.6    0.5   0.8   0.8

df3(所需輸出)

Date          A           B
01/01/2021    (39*0.1)    (100*0.3)
01/02/2021    (58*0.2)    (188*0.3)
01/03/2021    (220*0.6)   (300*0.8)
01/04/2021    (0*0.1)     (11*0.5)

實際上,我需要檢查 df1 中 A 和 B 的值,並根據日期與 df2 中的相應值相乘,以及該值是否介於 0 和 50、50 和 100 或 >100 之間(在 A 的情況下)。

實際上,df1 和 df2 遠遠超出了 2 項“A”和“B”,我打算在 for 循環中迭代 df1 的每一列,因此我正在尋找一個通用的解決方案。

謝謝

這是一種方法:

def fun(x):
   col_name = x.name
   col_idx = df.columns.get_loc(col_name)
   
   lower, middle, upper = df2.columns.get_loc_level(col_name)[1]
   cond_list = [upper <= x, middle <= x, lower <= x]
   choice_list =  np.arange(3)[::-1] + 3 * col_idx
   selections = np.select(cond_list, choice_list)

   cols_in_df2 = df2.columns[selections]
   rows_in_df2 = x.index
   multipliers_in_df2 = np.diag(df2.loc[rows_in_df2, cols_in_df2])
   
   result = x * multipliers_in_df2
   return result

df.apply(fun)

要得到

                A      B
Date
2021-01-01    3.9   30.0
2021-01-02   11.6   56.4
2021-01-03  132.0  240.0
2021-01-04    0.0    5.5

我們有一個cond_list條件,其限制是從df2 s 列中的相應值獲得的,以及一個choice_list ,它是df2中的相應列,例如對於Achoice_list[2, 1, 0] ,對於B ,它是[5, 4, 3] 我們通過3 * col_idx獲得列的偏移量,其中3是條件數。

然后我們執行select離子,這取決於這些給出我們應該尋找哪些列( cols_in_df2 )。 要查找的行是系列的index ,因此我們通過loc選擇multipliers_in_df2與這些。

最后,我們將手頭的系列乘以這些乘數並返回。

使用apply的每一列都會發生此過程。

暫無
暫無

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

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