使用for循环遍历列列表

时间:2019-04-17 06:43:00

标签: python-3.x pandas numpy dataframe

我正在使用for循环遍历列。我正在使用切片选择列。这是完美的工作。但是当我提供要迭代的列列表时,会失败并显示错误

  

IndexError:仅整数,切片(:),省略号(...),   numpy.newaxis(None)和整数或布尔数组是有效索引

我也尝试过使用整数列表,但是失败了。在这种情况下,如何迭代选定的列

代码:

for column in df1.columns[2:14]:

cols = ['a', 'b', 'c', 'd']

for column in df1.columns[cols]:

1 个答案:

答案 0 :(得分:0)

首先通过list选择列,然后获取列:

for column in df1[cols].columns:
    print (column)   

另一种解决方案也是可行的,但我认为可读性较差:

for column in df1[cols]:
    print (column)