2016-08-29 69 views
0

有沒有辦法做到在Python中的Excel搭配()函數,使得:python中的MATCH函數?

在這樣

K-Means Elbow Method results圖...

...其中我切斷在y = 90,我想打印哪個對應的x值最接近。

基於我的調查,值/答案應該是4,但我怎麼可能打印或存儲在一個變量?

In: print(bss/tss*100) 

Out: [ 1.21976032e-14 7.42743185e+01 8.51440985e+01 9.21584826e+01 
     9.59771981e+01 9.74117561e+01 9.82980987e+01 9.90505760e+01 
     9.92982678e+01 9.94756800e+01 9.96396123e+01 9.97126077e+01 
     9.97593424e+01 9.98030600e+01 9.98344280e+01 9.98692896e+01 
     9.98840717e+01 9.99020097e+01 9.99142963e+01] 
+0

Python本身不支持這個級別的數學調查。但是,NumPy和SciPy對基本的數值分析有各種支持。 ** SciPy.interpolate **是一種接近你所需要的。 – Prune

回答

0

你也可以用這個頭腦簡單的功能來擊敗它。 它發現至少與目標值一樣大的第一個值,檢查先前的值,並返回更接近值的位置(基於1而非0)。

def match (table, target): 
    for over in range(len(table)): 
     if table[over] >= target: 
      break 

    # over is the index of the first vale at least as large as the target 
    # return the position (index+1) of the nearer value 
    return over+1 if 2*target > table[over-1] + table[over] \ 
      else over 


ss_table = [ 
    1.21976032e-14, 7.42743185e+01, 8.51440985e+01, 9.21584826e+01, 
    9.59771981e+01, 9.74117561e+01, 9.82980987e+01, 9.90505760e+01, 
    9.92982678e+01, 9.94756800e+01, 9.96396123e+01, 9.97126077e+01, 
    9.97593424e+01, 9.98030600e+01, 9.98344280e+01, 9.98692896e+01, 
    9.98840717e+01, 9.99020097e+01, 9.99142963e+01 
] 

print match(ss_table, 87) 
print match(ss_table, 90) 

對於您的示例,根據需要返回3和4。

+0

真棒,非常感謝! – Carla

0

您正在查找argmin功能。

from numpy import * 

print argmin(abs(data - threshold)) 

會發現指數來自閾值偏差最小的。指定數學關係(argmin(abs(...)))要比將其隱藏在模糊的「匹配」功能中要精確得多。這樣,很清楚如何使用例如兩個閾值(上限和下限)或非常數閾值函數。我們可以找到最近的點兩個的功能相同。