【问题标题】:numpy equivalent of pandas相当于熊猫的numpy
【发布时间】:2015-11-08 14:29:19
【问题描述】:

我有以下 numpy 数组:

x = np.arange(9.).reshape(3, 3)

因此:

>>>> x
array([[ 0.,  1.,  2.],
       [ 3.,  4.,  5.],
       [ 6.,  7.,  8.]])

我想选择第三列大于 2 的所有行。

在熊猫中,我会这样做:

import pandas as pd
d = DataFrame(x)

>>>> d[d.iloc[:,2]>2]

输出将是:

   0  1  2
1  3  4  5
2  6  7  8

如何使用 numpy 获得相同的输出?我试过 numpy where 但它返回索引,而不是值。 谢谢!

【问题讨论】:

    标签: python numpy pandas subset


    【解决方案1】:
    In [120]:
    x[x[: , 2] > 2]
    Out[120]:
    array([[ 3.,  4.,  5.],
           [ 6.,  7.,  8.]])
    

    分解


    In [122]:
    mask = x[: , 2] > 2
    mask
    Out[122]:
    array([False,  True,  True], dtype=bool)
    
    In [123]:
    x[mask]
    Out[123]:
    array([[ 3.,  4.,  5.],
           [ 6.,  7.,  8.]])
    

    【讨论】:

    • 美丽 - 也很直观。非常感谢纳德!
    猜你喜欢
    • 2018-02-02
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多