Python numpy ravel功能未展平数组

问题描述 投票:0回答:1

我有一个名为x的数组的数组,我正在尝试对它进行排序,但是结果是相同的x。它没有使任何东西变扁平。我也尝试过函数flatten()。有人可以解释一下为什么会这样吗?

x = np.array([np.array(['0 <= ... < 200 DM', '< 0 DM', 'no checking account'], dtype=object),
       np.array(['critical account/ other credits existing (not at this bank)',
       'existing credits paid back duly till now'], dtype=object),
       np.array(['(vacation - does not exist?)', 'domestic appliances'],
      dtype=object)], dtype=object)

np.ravel(x)

我实际上正在尝试重现此问题中的代码:One-hot-encoding multiple columns in sklearn and naming columns但是我被ravel()阻止了。

谢谢

python numpy
1个回答
0
投票
In [455]: x = np.array([np.array(['0 <= ... < 200 DM', '< 0 DM', 'no checking account'], dtype=object),
     ...:  
     ...:        np.array(['critical account/ other credits existing (not at this bank)', 
     ...:        'existing credits paid back duly till now'], dtype=object), 
     ...:        np.array(['(vacation - does not exist?)', 'domestic appliances'], 
     ...:       dtype=object)], dtype=object)                                                          
In [456]: x                                                                                            
Out[456]: 
array([array(['0 <= ... < 200 DM', '< 0 DM', 'no checking account'], dtype=object),
       array(['critical account/ other credits existing (not at this bank)',
       'existing credits paid back duly till now'], dtype=object),
       array(['(vacation - does not exist?)', 'domestic appliances'],
      dtype=object)], dtype=object)
In [457]: x.shape                                                                                      
Out[457]: (3,)
In [458]: [i.shape for i in x]                                                                         
Out[458]: [(3,), (2,), (2,)]

x是具有3个元素的1d数组。这些元素本身是具有不同形状的数组。

扁平化的一种方法是:

In [459]: np.hstack(x)                                                                                 
Out[459]: 
array(['0 <= ... < 200 DM', '< 0 DM', 'no checking account',
       'critical account/ other credits existing (not at this bank)',
       'existing credits paid back duly till now',
       '(vacation - does not exist?)', 'domestic appliances'],
      dtype=object)
In [460]: _.shape                                                                                      
Out[460]: (7,)
© www.soinside.com 2019 - 2024. All rights reserved.