To do what you're asking, just use the phrase

labeledArray = [0, x]

This way, you will get a standard list with 0 as the first element and a Numpy array as the second element.

However, in practice, you are probably trying to label for the purpose of later recall. In that case, I'd recommend you use a dictionary, as it is less confusing to keep track of:

myArrays = {}
myArrays[0] = x

Which can be used as follows:

>>> myArrays
{0: array([[1, 2, 3, 4],
   [5, 6, 7, 8]])}
>>> myArrays[0]
array([[1, 2, 3, 4],
   [5, 6, 7, 8]])
Answer from Naveen Arun on Stack Overflow
Top answer
1 of 2
5

The warning you're being given is to tell you you're using a deprecated (to be removed) syntax. It suggests you use from_dict instead, for example

import numpy as np
import pandas as pd
a=pd.DataFrame.from_dict({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
},
orient='index', columns=['one', 'two', 'three'])
print(a)

This will give your intended output

   one  two  three
A    1    2      3
B    4    5      6

Explanation

The following block which you say you don't understand —

a = pd.DataFrame.from_dict({
        'A': [1, 2, 3],
        'B': [4, 5, 6]
},
orient='index', columns=['one', 'two', 'three'])
print(a)

This creates a DataFrame from a dictionary (from_dict) which we're passing in as the first parameter.

{'A': [1, 2, 3], 'B': [4, 5, 6]}

This dictionary has 2 entries, "A" and "B", each of which contain a list of numbers. If you pass this to pd.DataFrame.from_dict by itself, e.g.

a = pd.DataFrame.from_dict({
        'A': [1, 2, 3],
        'B': [4, 5, 6]
})
print(a)

You would get the following output.

   A  B
0  1  4
1  2  5
2  3  6

As you can see, the keys for the dictionary are being output as the column headers. To use the dictionary keys as (row) index headers and rotate the data you can pass in orient='index'.

a = pd.DataFrame.from_dict({
        'A': [1, 2, 3],
        'B': [4, 5, 6]
}, orient='index')
print(a)

This will give the following output.

   0  1  2
A  1  2  3
B  4  5  6

The final step is to pass in the column headers we want to use.

a = pd.DataFrame.from_dict({
        'A': [1, 2, 3],
        'B': [4, 5, 6]
},
orient='index', columns=['one', 'two', 'three'])
print(a)

Which gives the intended output

   one  two  three
A    1    2      3
B    4    5      6
2 of 2
4

data = {'A': [1,2,3], 'B': [4,5,6]}

pd.DataFrame.from_dict(data,orient='index',columns=['one', 'two', 'three'])

🌐
SciPy
docs.scipy.org › doc › scipy › reference › generated › scipy.ndimage.label.html
label — SciPy v1.18.0 Manual
label has experimental support for Python Array API Standard compatible backends in addition to NumPy. Please consider testing these features by setting an environment variable SCIPY_ARRAY_API=1 and providing CuPy, PyTorch, JAX, or Dask arrays as array arguments.
🌐
Stack Overflow
stackoverflow.com › questions › 56109029 › how-to-add-label-to-numpy-ndarray › 56109899
python - How to add label to numpy.ndarray? - Stack Overflow
I just trying to add label to numpy.ndarray. numpy.ndarray's shape is (?, 1, 100, 100) [[[ 1 1 1 ... 1 1 1] ... [ 1 1 1 ... 1 1 1]]] ... I tried like this but doesn't work. data_train = [] for i in range(len(true_data.tolist())): true_data[i].append([1,0]) data_train.append(true_data[i]) ... I suppose you're training a classifier. Why don't you simply use two different arrays for your inputs and your labels?
🌐
YouTube
youtube.com › watch
Adding Labels Before Numpy Arrays: A Simple Approach - YouTube
Learn how to easily add custom labels before Numpy array outputs, making your data presentation clearer and more engaging.---This video is based on the quest...
Published: September 5, 2025
Views: 1
🌐
Stack Overflow
stackoverflow.com › questions › 70374912 › label-elements-within-a-group-in-numpy
python - Label elements within a group in numpy - Stack Overflow
You need to find a way to subtract maximum indices of each group before counting np.cumsum. np.add.reduceat allows you to find these results without a need to split array before. If you pass indices that separates your groups in it, you'll get sum of every group. def refresh_groups(label: np.array, mask_group: np.array): mark_idx = np.flatnonzero(mask_group) reducer = np.add.reduceat(label, mark_idx) label[mark_idx[1:]] -= reducer[:-1] def np_label(arr: np.array, group: np.array, replace_zero: bool = True, replace_group: bool = True): arr_shift = shift(arr, 1, fill_value=0) label = np.where(ar
Find elsewhere
Top answer
1 of 3
16

What you may be looking for is xarray.


From its documentation:

xarray: N-D labeled arrays and datasets in Python

xarray (formerly xray) is an open source project and Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!

Xarray introduces labels in the form of dimensions, coordinates and attributes on top of raw NumPy-like arrays, which allows for a more intuitive, more concise, and less error-prone developer experience. The package includes a large and growing library of domain-agnostic functions for advanced analytics and visualization with these data structures.

Xarray was inspired by and borrows heavily from pandas, the popular data analysis package focused on labelled tabular data. It is particularly tailored to working with netCDF files, which were the source of xarray’s data model, and integrates tightly with dask for parallel computing.

2 of 3
1

numpy arrays are the abstract objects that you can use to build labeled tables and plots. pandas pushes the table and data series angle, matplotlib the plotting angle. And for large scale data storage, such as generated by supercomputer models, there are systems like NETCDF and HDF5.

You might want to look at how HDF5 handles dimension scales, and how h5py gives you access to them in numpy.

http://docs.h5py.org/en/latest/high/dims.html

Datasets are multidimensional arrays. HDF5 provides support for labeling the dimensions and associating one or “dimension scales” with each dimension. A dimension scale is simply another HDF5 dataset.

Creating an array from axes is a common numpy task. np.arange and np.linspace create 1d arrays, np.meshgrid, mgrid and ogrid create 2d (or larger) arrays, which in turn are used to calculate values on a grid. Note that meshgrid allows you to specify ij or xy styles, reflecting two conventions, rows/columns v plot horizontal/vertical axes.

 X, Y = np.meshgrid(x,y)
 z = my_function(X,Y)

but plotting functions can take various forms of input:

 plot(x, y, z)   # 2 1d arrays and a 2d
 scatter(X,Y,Z)  # 3 2d arrays
 scatter(XYZ)    # 1 Nx3 array

So while this is a connection between the generating arrays and dependent one, this is a higher level of organization, one that your code has to maintain, not something that numpy does for you.

A comment mentioned structured arrays. That can replace the columns of a 2d array with named fields (and by extension to higher dimensions), but it is most useful when working with diverse data loaded from CSV files. They are more like the fields of SQL tables than the y coordinate of a plot.

🌐
Stack Exchange
gis.stackexchange.com › questions › 373912 › save-the-array-labels-in-a-new-array
python - Save the array labels in a new array - Geographic Information Systems Stack Exchange
labeling · numpy · array · save · Share · Improve this question · Follow · edited Sep 12, 2020 at 13:54 · asked Sep 12, 2020 at 11:37 · vins_26 · 44333 silver badges1212 bronze badges 1 · 1 · Store them in a dictionary d = {} for c in np.unique(arr): d['cls{}'.format(int(c))] = arr==c · Bera – Bera · 2020-09-12 14:32:42 +00:00 Commented Sep 12, 2020 at 14:32 · Add a comment | Sorted by: Reset to default ·
🌐
Stack Overflow
stackoverflow.com › questions › 57483795 › create-numpy-array-with-class-label-and-dataset
python - Create numpy array with class label and dataset - Stack Overflow
August 14, 2019 - train_split_path = os.path.join(root_dir, 'splits', 'train.txt') with open(train_split_path, 'r') as train_split: train_classes = [line.rstrip() for line in train_split.readlines()] #number of classes no_of_classes = len(train_classes) #number of examples num_examples = 20 #image width img_width = 28 #image height img_height = 28 channels = 1 train_dataset = np.zeros([no_of_classes, num_examples, img_height, img_width], dtype=np.float32) for label, name in enumerate(train_classes): alphabet, character, rotation = name.split('/') rotation = float(rotation[3:]) img_dir = os.path.join(root_dir, '
🌐
Renaissanceplanning
renaissanceplanning.github.io › emma-docs › labeled_array.html
Labeled Arrays — EMMA 0.1.0 documentation
An existing array (including an on-disk pytables array) can be used to construct the labeled array. Alternatively the user can pass an array constructor, such as np.ones, to initialize a new array. The data attribute for an LbArray is always a pytables array. If a numpy array or constructor are given as data, an in-memory array is generated from the original data.