如何切片2D Python数组?失败:"TypeError:列表索引必须是整数,而不是元组". [英] How to slice a 2D Python Array? Fails with: "TypeError: list indices must be integers, not tuple"

查看:188
本文介绍了如何切片2D Python数组?失败:"TypeError:列表索引必须是整数,而不是元组".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在numpy模块中有一个二维数组,如下所示:

I have a 2d array in the numpy module that looks like:

data = array([[1,2,3],
              [4,5,6],
              [7,8,9]])

我想获得仅包含元素的某些列的此数组的一部分.例如,我可能想要第0列和第2列:

I want to get a slice of this array that only includes certain columns of element. For example I may want columns 0 and 2:

data = [[1,3],
        [4,6],
        [7,9]]

最Python化的方法是什么? (请不要循环)

What is the most Pythonic way to do this? (No for loops please)

我认为这会起作用:

newArray = data[:,[0,2]]

但是它会导致:

TypeError: list indices must be integers, not tuple

推荐答案

错误明确指出:数据不是numpy数组,而是列表列表.

The error say it explicitely : data is not a numpy array but a list of lists.

首先尝试将其转换为numpy数组:

try to convert it to an numpy array first :

numpy.array(data)[:,[0,2]]

这篇关于如何切片2D Python数组?失败:"TypeError:列表索引必须是整数,而不是元组".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆