簡體   English   中英

根據其他數據框中提供的范圍值創建新列

[英]Creating a new column based on range values provided in other dataframe

我有兩個數據框,其中一個數據框用作參考表,另一個包含實際值。

>>> reference_table
   MinRange  MaxRange  Multiplier Group
0        10        30           2     A
1        10        40           4     B
2        10        14          10     C
3        15        19           8     C
4        20        24           6     C

>>> df2
  Group  Element  Value
0     A       15      7
1     B       37      8
2     C       12      9
3     C       23     10

在這里,我要在data框中創建一個新列“ Updated Value ,如下所示:

>>> data
  Group  Element  Value  Updated Value
0     A       15      7             14
1     B       37      8             32
2     C       12      9             90
3     C       23     10             60

更新值的創建如下-

第1行:Element = 15&Group = A,位於Group A的參考表的MinRange和MaxRange中。因此,更新后的Value = Value * Multiplier = 7 * 2 = 14

第2行:Element = 37&Group = B,位於Group B的參考表的MinRange和MaxRange中。因此,更新后的Value = Value * Multiplier = 8 * 4 = 32

第3行:Element = 12&Group = C,位於Group C(索引2 )參考表的MinRange(10)和MaxRange(14)中。 因此,更新后的值=值*乘數= 9 * 10 = 90

第4行:Element = 23&Group = C,位於Group C(索引4 )參考表的MinRange(10)和MaxRange(14)中。 因此,更新后的值=值*乘數= 10 * 6 = 60

如何使用熊貓創建這樣的列? 我嘗試了幾種方法,但沒有一種起作用。 很高興指出任何參考或類似問題。

mergequery開始的解決方案:

res = pd.merge(df1, df2, on='Group')
res = res.query('MinRange <= Element <= MaxRange')
res['Updated Value'] = res['Value'] * res['Multiplier']
res = res[['Group', 'Element', 'Value', 'Updated Value']].reset_index(drop=True)

res
  Group  Element  Value  Updated Value
0     A       15      7             14
1     B       37      8             32
2     C       12      9             90
3     C       23     10             60

暫無
暫無

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

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