2016-08-29 27 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(...)))要比将其隐藏在模糊的“匹配”功能中要精确得多。这样,很清楚如何使用例如两个阈值(上限和下限)或非常数阈值函数。我们可以找到最近的点两个的功能相同。