简体   繁体   English

将第三维添加到二维 numpy.ndarray

[英]Add third dimension to a 2-dimensional numpy.ndarray

I have an array which contains 50 time series.我有一个包含 50 个时间序列的数组。 Each time series has 50 values.每个时间序列有 50 个值。 The shape of my array is therefore:因此,我的数组的形状是:

print(arr.shape) = (50,50)

I want to extract the 50 time series and I want to assign a year to each of them:我想提取 50 个时间序列,并为每个时间序列分配一年:

years = list(range(1900,1950))
print(len(years)) = 50

The order should be maintained.秩序应该维持。 years[0] should correspond with arr[0,:] (this is the first time series). years[0]应该对应于arr[0,:] (这是第一个时间序列)。

I am glad for any help!我很高兴有任何帮助!

Edit: This is the small example编辑:这是小例子

import random

years = list(range(1900,1904))
values = random.sample(range(10, 30), 16) 
arr = np.reshape(values, (4, 4))

Let's say you have the following data:假设您有以下数据:

import numpy as np

data = np.random.randint(low=1, high=9, size=(5, 4))
years = np.arange(1900, 1905)

You can use np.concatenate :您可以使用np.concatenate

>>> arr = np.concatenate([years[:, None], data], axis=1)
>>> arr

array([[1900,    5,    8,    1,    2],
       [1901,    3,    3,    1,    5],
       [1902,    7,    4,    7,    5],
       [1903,    1,    6,    6,    4],
       [1904,    4,    5,    3,    8]])

or maybe use a pandas.DataFrame :或者可能使用pandas.DataFrame

>>> import pandas as pd

>>> df = pd.DataFrame(data)
>>> df = df.assign(year=years)
>>> df = df.set_index("year")
>>> df

      0  1  2  3
year
1900  3  2  8  1
1901  5  8  5  2
1902  3  5  4  3
1903  6  2  7  6
1904  8  8  4  6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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