简体   繁体   English

保留numpy 2D数组的顺序

[英]Preserving sequential order of numpy 2D arrays

Given this 2D numpy array: 给定此二维numpy数组:

a=numpy.array([[31,22,43],[44,55,6],[17,68,19],[12,11,18],...,[99,98,97]])

given the need to flatten it using numpy.ravel : 鉴于需要使用numpy.ravel将其展平:

b=numpy.ravel(a)

and given the need to later dump it into a pandas dataframe, how can I make sure the sequential order of the values in a is preserved when applying numpy.ravel ? 并且考虑到以后需要将其转储到pandas数据帧中的问题, 当应用numpy.ravel如何确保保留a值的顺序? eg, How can I check/ensure that numpy.ravel does not mess up with the original sequential order? 例如,如何检查/确保numpy.ravel不会弄乱原始顺序?

Of course the intended result should be that the numbers coming before and after 17 in b , for instance, are the same as in a . 当然,预期的结果应该是这些数字来之前和之后17b ,例如,是一样a

First of all you need to formulate what "sequential" order means for you, as numpy.ravel() does preserve order. 首先,您需要制定“顺序”顺​​序对您的含义,因为numpy.ravel()确实保留了顺序。 Here is a tip how to formulate what you need: try with a simplest possible toy example: 这里有一个提示,提示您如何制定所需的内容:尝试一个最简单的玩具示例:

import numpy as np
X = np.arange(20).reshape(-1,4)

X
#array([[ 0,  1,  2,  3],
#   [ 4,  5,  6,  7],
#   [ 8,  9, 10, 11],
#   [12, 13, 14, 15],
#   [16, 17, 18, 19]])
X.ravel()
# array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 
#        13, 14, 15, 16, 17, 18, 19])

Does it meet your expectation? 符合您的期望吗? Or you want to see this order: 或者您想查看此顺序:

Z = X.T
Z
# array([[ 0,  4,  8, 12, 16],
#        [ 1,  5,  9, 13, 17],
#        [ 2,  6, 10, 14, 18],
#        [ 3,  7, 11, 15, 19]])
Z.ravel()
# array([ 0,  4,  8, 12, 16,  1,  5,  9, 13, 17,  2,  6, 10, 
#         14, 18,  3,  7, 11, 15, 19])

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

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