【问题标题】:Python numpy ravel function not flattening arrayPython numpy ravel函数不展平数组
【发布时间】:2020-07-29 23:30:59
【问题描述】:

我有一个名为 x 的数组数组,我正在尝试对其进行 ravel,但结果是相同的 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() 挡住了。

谢谢

【问题讨论】:

  • 好吧,您创建了一个对象数组,而不是二维数组。因此它是扁平的,因为对于 numpy 对象是数组中的项目。它们碰巧是数组这一事实并不重要。
  • 感谢您的评论。我怎样才能重现链接中问题的回复?据我所知,这是我所拥有的情况,并且在这种情况下有效。

标签: python numpy


【解决方案1】:
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 个元素的一维数组。这些元素本身就是数组,具有不同的形状。

一种扁平化方法是:

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,)

【讨论】:

    猜你喜欢
    • 2019-01-11
    • 1970-01-01
    • 2019-08-26
    • 2016-02-16
    • 2014-08-29
    • 2020-04-27
    • 1970-01-01
    • 2020-01-25
    • 2017-12-26
    相关资源
    最近更新 更多