简体   繁体   中英

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.

 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. 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]. 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

 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:

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 .

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM