在xlwings中加速自定义项

2024-10-04 13:27:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着从Xlwings中尝试一些特性。我想使用一个来自numpy的通用函数,它允许快速插值(numpy.INTP公司). 在

@xlfunc
def interp(x, xp,yp):
    """Interpolate vector x on vector (xp,yp)"""
    y=np.interp(x,xp,yp)
    return y

@xlfunc
def random():
    """Returns a random number between 0 and 1"""
    x=np.random.randn()
    return x   

例如,我创建了两个向量(xp,yp)(在Excel中) 800行

^{pr2}$

在第三列中,我创建另一个向量(60行),随机数为0和800(按升序排列) 给了我这样的感觉:

Third Column    
17.2    
52.6    
75.8    
[...]

我想把第三列插入第一列。所以

Fourth Column    
=interp(C1,A1:A800,B1:B800)    
=interp(C2,A1:A800,B1:B800)    
=interp(C3,A1:A800,B1:B800)    
[...]

这很容易做到。但如果我有10列或更多的列来插值,可能会花费太多时间。我相信有更好的方法来做这件事。一个主意?在

谢谢你的帮助!在

编辑:

我试过了,但没用”xw.范围[…].value=y“

@xw.xlfunc
def interpbis(x, xp,yp):
    """Interpolate scalar x on vector (xp,yp)"""
    thisWB=xw.Workbook.active()
    thisSlctn=thisWB.get_selection(asarray=True)
    sheet=thisSlctn.xl_sheet.name
    r = thisSlctn.row
    c = thisSlctn.column
    y=np.interp(x,xp,yp)
    xw.Range(sheet,(r,c)).value=y
    return None

Tags: returndefa1nprandomxpb1vector
1条回答
网友
1楼 · 发布于 2024-10-04 13:27:16

简单的回答是:使用Excel的数组函数。在

长话短说是: 首先,更新到xlwings v0.6.4(否则,我将展示的random()将不起作用)。然后更改您的函数如下:

from xlwings import Application, Workbook, xlfunc
import numpy as np

@xlfunc
def interp(x, xp, yp):
    """Interpolate vector x on vector (xp,yp)"""
    y = np.interp(x, xp, yp)
    return y[:, np.newaxis]  # column orientation

@xlfunc
def random():
    """Returns a random number between 0 and 1"""
    app = Application(Workbook.caller())
    # We shall make this easier in a future release (getting the array dimensions)
    r = app.xl_app.Caller.Rows.Count
    c = app.xl_app.Caller.Columns.Count
    x = np.random.randn(r, c)
    return x

现在使用Excel中的数组公式,如hereCtrl+Shift+Enter)所述。在

相关问题 更多 >