Home > Software engineering >  ValueError: condition must be a 1-d array
ValueError: condition must be a 1-d array

Time:06-18

Hi I've been stuck on this error for a while now! I want to interpolate data 3 D and then display it in 2D (in Basemap). Unfortunately, I get this error when I want to plot the grid[long], grid[lat] and the interpolation values with contourf:

ValueError: condition must be a 1-d array

I already tried to import the values as y = df['variable'].values.tolist() but this did not change the error. Unfortunately, as I am new to arrays, I do not have a good understanding of them and need to solve this error in a timely manner.

def load_data():
    df = pd.read_csv(r"File")
    return(df)

def get_data(df):
    return {
        "lons": df['Longitude'],
        "lats": df['Latitude'],
        "alts": df['Altitude'],
        "values": df['O18'],
    }

def generate_grid(data, basemap, delta=1):
    grid = {
        'lon': np.arange(-180, 180, delta),
        'lat': np.arange(np.amin(data["lats"]), np.amax(data["lats"]), delta), 
        'alt': np.arange(np.amin(data["alts"]), np.amax(data["alts"]), delta)
    }
    grid["x"], grid["y"], grid["z"] = np.meshgrid(grid["lon"], grid["lat"], grid["alt"], indexing="ij")
     grid["x"], grid["y"]  = basemap(grid["x"], grid["y"])
    return grid

def interpolate(data, grid):
    uk3d = UniversalKriging3D(
        data["lons"],
        data["lats"],
        data["alts"],
        data["values"],
        variogram_model='exponential',
        drift_terms=["specified"],
        specified_drift=[data["alts"]],
    )
    return uk3d.execute("grid", grid["lon"], grid["lat"], grid["alt"], specified_drift_arrays=[grid["z"]])

def prepare_map_plot():
    figure, axes = plt.subplots(figsize=(10,10))
    basemap = Basemap(projection='robin', lon_0=0, lat_0=0, resolution='h',area_thresh=1000,ax=axes) 
    return figure, axes, basemap

def plot_mesh_data(interpolation, grid, basemap):
    colormesh = basemap.contourf(grid["x"], grid["y"], interpolation,32, cmap='RdBu_r') 
    color_bar = my_basemap.colorbar(colormesh,location='bottom',pad="10%") 

The error Message:

    >>> plot_mesh_data(interpolation, grid,basemap)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in plot_mesh_data
  File "C:\Users\Name\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\mpl_toolkits\basemap\__init__.py", line 548, in with_transform
    return plotfunc(self,x,y,data,*args,**kwargs)
  File "C:\Users\Name \AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\mpl_toolkits\basemap\__init__.py", line 3666, in contourf
    xl = xx.compress(condition).tolist()
ValueError: condition must be a 1-d array

CodePudding user response:

Hmm.. Seems to be a problem with np.compress

condition needs to be a 1-d array of bools according to: https://numpy.org/doc/stable/reference/generated/numpy.compress.html#numpy.compress This is what happens to grid['x']

xx = x[x.shape[0]//2,:]
condition = (xx >= self.xmin) & (xx <= self.xmax) 

So i would do this to your grid["x"] like:

```
def plot_mesh_data(interpolation, grid, basemap):
x = grid["x"]
xx = x[x.shape[0]//2,:]
condition = (xx >= self.xmin) & (xx <= self.xmax) 
print(condition)
colormesh = basemap.contourf(grid["x"], grid["y"], interpolation,32, 
cmap='RdBu_r')
color_bar = basemap.colorbar(colormesh,location='bottom',pad="10%") 


```

Outside of your function to see why it is not a 1-D array of booleans. so the print should give you smt like: [(True, False, True), type=ndarray)] or [True, False, True] etc.

Update since the self pointer was missing. This normally occurs when you try to act on an class method without having the object correctly instanciated. i.e.: import Class as Class_imp Class_imp.dosmt()

Will give you positional argument self missing. SInce you did not do: my_class_imp = Class_imp() my_class_imp.dosmt() Do you have a part in your complete script at bottom that does

if __name__ == '__main__':
  df = get_data and data = load_data 
  fig, ax, basemap = prepare_map_plot()
  interpol = interpolate(data, grid) 
  grid = generate_grid(data, basemap, delta=1) 
  plot_mesh_data(interpol, grid, basemap)

you can run this like

>>> import runpy
>>> runpy.run_path(path_name='path_to_script.py')

Cheers

  • Related