python - 高级 numpy/pandas 索引

标签 python numpy pandas scipy

我想执行类似的索引操作

ix = [(1,2),(3,4),(5,6)]
ar[ix] # this is invalid real life

这会给我一维数组

array([ar[1,2], ar[3,4], ar[5,6]])

换句话说,我想指定一组坐标并返回这些坐标处的值向量。这是行不通的,我对索引 ix 的精确性并不挑剔,任何对列表、列表对、二维数组、pandas.DataFrame 都可以。我有兴趣在 numpy 数组和 Pandas DataFrame 上执行此操作。

最佳答案

对于 numpy,这可以通过非常相似的方式完成:

>>> a = np.arange(5*5).reshape(5,5)
>>> ix = [(1,2),(3,4),(2,4)]
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

>>> a[zip(*ix)]
array([ 7, 19, 14])

对于 pandas,您可以通过访问底层 numpy 数组以类似的方式获取值:

>>> import pandas as pd
>>> df = pd.DataFrame(a)
>>> df.values[zip(*ix)]
array([ 7, 19, 14])

对于 2D 数组 numpy 需要一个行索引列表,然后是列索引,使用 zip(*ix) 您可以提供以下内容:

>>> zip(*ix)
[(1, 3, 2), (2, 4, 4)]

关于python - 高级 numpy/pandas 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23553036/

相关文章:

python - 如何记录引发 KeyError 的值

python - Pandas -将列旋转成(条件)聚合字符串

python - 查找有关 Python WebDriver API 的信息

Python Twitter 工具和 gzip 错误 "IOError: CRC check failed"

python - python for循环中的count函数

python - 使用Numpy不重复生成两个数组的随机组合

python - 如何 reshape 图像的尺寸以包含图像数量(即 1)?

python - 获得一组线性方程的非平凡解

python - 添加新事件/日志后刷新 TensorBoard 的最佳方法是什么?

python - 如何根据两列进行计算创建Dataframe?