Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将2D numpy数组重新排列为保持行索引的列向量_Python_Arrays_Numpy_Reshape - Fatal编程技术网

Python 将2D numpy数组重新排列为保持行索引的列向量

Python 将2D numpy数组重新排列为保持行索引的列向量,python,arrays,numpy,reshape,Python,Arrays,Numpy,Reshape,我有一个如下形式的numpy数组: 我想重新安排它,以便将列堆叠在一起,保持它们的初始索引(可能是新列) 我想以这样的方式结束: Jan2017 | 0 | 0 Feb2017 | 0 | 1 Mar2017 | 0 | 1 ... Jan2017 | 1 | 0 Feb2017 | 1 | 0 etc 如果第一列和第二列表示初始数组的索引,则表示矩阵保存在A中,然后通过A.transpose().flatte() 您可以堆叠索引数组以及(可能)数据帧中的展平和转置值 例如: 作为pd进口

我有一个如下形式的numpy数组:

我想重新安排它,以便将列堆叠在一起,保持它们的初始索引(可能是新列)

我想以这样的方式结束:

Jan2017 | 0 | 0
Feb2017 | 0 | 1
Mar2017 | 0 | 1
...
Jan2017 | 1 | 0 
Feb2017 | 1 | 0 etc

如果第一列和第二列表示初始数组的索引,则表示矩阵保存在
A
中,然后通过
A.transpose().flatte()


您可以堆叠索引数组以及(可能)
数据帧中的展平和转置值

例如:

作为pd进口熊猫

df = pd.DataFrame({0: [0,1,1,0,0,1,0],
                   1: [0,0,0,0,0,1,0],
                   2: [1,0,1,0,1,0,0]},
                  index=['Jan2017', 'Feb2017', 'Mar2017', 'Apr2017', 'May2017', 'Jun2017', 'Jul2017'])
可以这样处理:

>>> np.stack([np.repeat(np.arange(len(df.columns)), len(df)), df.values.T.ravel()], axis=1)
array([[0, 0],
       [0, 1],
       [0, 1],
       [0, 0],
       [0, 0],
       [0, 1],
       [0, 0],
       [1, 0],
       [1, 0],
       [1, 0],
       [1, 0],
       [1, 0],
       [1, 1],
       [1, 0],
       [2, 1],
       [2, 0],
       [2, 1],
       [2, 0],
       [2, 1],
       [2, 0],
       [2, 0]], dtype=int64)
用于创建索引:

>>> np.repeat(np.arange(len(df.columns)), len(df))
array([0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])
将阵列转置并展平:

>>> df.values.T.ravel()
array([0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0], dtype=int64)

然后使用

按行堆叠(因此,
轴=1
)请提供一个非常简单的示例,使用类似于
np.arange(15)的数组。重塑((3,5))
,使其看起来更像熊猫数据帧(或类似的数组)。
>>> df.values.T.ravel()
array([0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0], dtype=int64)