[英]How to: Given a value (x,y,z) from an arry [U,x,y,z] output associated value of U
This seems like it's simple but I'm looking for a very computationally efficient (fast) way to do this. 这似乎很简单,但我正在寻找一种计算效率很高(快速)的方式来实现。 I have a set of data organized as such as a N by 4 numpy array.
我有一组数据,例如N x 4 numpy数组。
data = [[U[0],x[0],y[0],z[0],
U[1],x[1],y[1],z[1],
....
U[N],x[N],y[N],z[N]]]
What I would like to do is write a function that will take the actual numeric values of some given combination of elements x[N],y[N],z[N] as input and output the numeric value of U[N] that is in that same row. 我想做的是编写一个函数,该函数将元素x [N],y [N],z [N]的某些给定组合的实际数值作为输入,并输出U [N]的数值在同一行中。 There is no analytic function describing the data, it is purely numeric and so all I need is to give some combination of physical positional values say (x[51],y[51],z[51]) that will output the value of U that is in the row that has x[51], y[51], z[51].
没有描述数据的解析函数,它是纯数字的,因此我所需要的只是给出一些物理位置值的组合,例如(x [51],y [51],z [51]),将输出具有x [51],y [51],z [51]的行中的U。 An example on how it should work is given below: Say x[51] = 2.4, y[51] = 6.3, z[51] = 9.45 and U[51] = 13.665
下面给出一个有关其工作方式的示例:假设x [51] = 2.4,y [51] = 6.3,z [51] = 9.45和U [51] = 13.665
input >>
function(2.4,6.3,9.45)
output >>
13.665
So the goal is essentially for me to figure out how to write the function that would do this in an efficient way! 因此,从本质上讲,我的目标是找出如何编写可以有效实现此功能的函数!
If you expect to do a lot of searching, you could store the U
values in a dictionary and look them up with the x
, y
and z
values, like this: 如果希望进行大量搜索,则可以将
U
值存储在字典中,并使用x
, y
和z
值查找它们,如下所示:
import numpy as np
data = np.array([
[ 1.234, 3.7, 9.1, 2.74],
[13.665, 2.4, 6.3, 9.45],
[12.431, 8.1, 5.3, 4.25]
])
search_dict = dict(zip(map(tuple, data[:, 1:4]), data[:, 0]))
# or search_dict = {tuple(row[1:4]): row[0] for row in data}
search_dict[(2.4, 6.3, 9.45)]
# 13.665
Alternatively, this is a good job for pandas: 另外,这对熊猫来说是一项好工作:
import pandas as pd
df = pd.DataFrame(data, columns=['U', 'x', 'y', 'z']).set_index(['x', 'y', 'z'])
df.loc[(2.4, 6.3, 9.45), 'U']
Building the dictionary or DataFrame will take some time and memory, but then you will get very fast results for each search, regardless of the length of data
. 构建字典或DataFrame会花费一些时间和内存,但是无论
data
长度如何,每次搜索都会得到非常快的结果。
If you have a big array and not many searches, you could use a brute-force search: 如果阵列很大且搜索不多,则可以使用蛮力搜索:
matched_rows = (data[:, 1:4]==np.array([2.4, 6.3, 9.45])).all(axis=1)
data[matched_rows, 0]
# array([13.665])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.