提高从函数创建多维数组的效率

2024-05-04 10:55:04 发布

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

这将是一个相当基本的问题,但我有点被两件事卡住了

我有一些数据存储在2D数组中,我们把它叫做z。我有两个独立的2D数组,nxpnyp,它们保存z中每个元素的映射信息nxpnyp因此目前持有笛卡尔坐标,我想将其转换为极坐标。 Following this,我已经定义了{}将给定的(x,y)转换为(r,θ),如下所示:

import numpy as np
import math

def polar(x, y):
    '''
    Args:
        x (double): x-coordinate.
        y (double): y-coordinate.

    Returns:
        r, theta (in degrees).
    '''
    r = np.hypot(x, y)
    theta = math.degrees(math.atan2(y, x))
    return r, theta

但从这一点上看,我认为我所做的一切都是解决这个问题的一个非常糟糕的方法。理想情况下,我只想输入笛卡尔数组并返回极轴数组,但这似乎不适用于我定义的函数(这可能是因为我隐式地将输入类型定义为double,但我希望python能够在这里重载)

r, theta = polar(nxp, nyp)

回溯是:

.... in polar
theta = math.degrees(math.atan2(y,x))

TypeError: only size-1 arrays can be converted to Python scalars

因此,我现在正在实现将所有内容转换为1D列表,并迭代填充rtheta。例如

nxp_1D = nxp.ravel()
nyp_1D = nyp.ravel()

for counter, value in enumerate(nxp_1D):
    r, theta = polar(value, nyp_1D[counter])

这个精确的实现是错误的,因为它只为rtheta返回一个值,而不是填充一个值列表

更一般地说,尽管出于几个原因,我确实不喜欢这种方法。看来这是解决这个问题的一个非常严厉的办法。除此之外,我可能希望稍后进行一些contourf绘图,这需要将rtheta转换回其原始数组形状

有没有一种更简单、更有效的方法来创建2D数组rtheta?是否可以通过更改我的polar函数定义或使用列表理解来创建它们

谢谢你的回复


Tags: 方法inimportcoordinate列表定义npmath
1条回答
网友
1楼 · 发布于 2024-05-04 10:55:04

是的,好的,所以这是一个非常简单的解决方法。感谢@user202729和@Igor Raush。这很简单:

def polar(x, y)
    r = np.hypot(x, y)
    theta = np.arctan2(y, x)
    return r, theta

.....
r, theta = polar(nxp, nyp)

对不起,这个问题太愚蠢了,但谢谢你的回答

相关问题 更多 >