【问题标题】:iterate over a list of columns using for loop使用 for 循环遍历列列表
【发布时间】:2019-09-07 08:06:59
【问题描述】:

我正在使用 for 循环来遍历列。我正在使用切片选择列。这是完美的工作。但是当我提供一个列(cols)列表来迭代它失败并出现错误

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

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

代码:

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

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

for column in df1.columns[cols]:

【问题讨论】:

  • 试试:for column in df1[cols]:

标签: python-3.x pandas numpy dataframe


【解决方案1】:

先按list选择列,然后获取列:

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

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

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

【讨论】:

  • 谢谢,但“for column in columns”终于奏效了。这里的“列”是列的列表
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-14
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2020-12-15
  • 2017-03-05
  • 2021-04-02
相关资源
最近更新 更多