使用Python中的索引循环选择两列的代码部分:

huangapple go评论71阅读模式
英文:

For loop to select two cols at a time using index in python

问题

选择第1列和第2列,第1列和第3列,第1列和第4列,以此类推,在一个pandas数据框中... 直到最后一列。
基本上,我需要在以下命令中循环2,从第2列开始,直到最后一列:

newdf = df.iloc[:,[1,2]] # 从索引2开始循环列索引,直到最后一列
英文:

Select 1st and 2nd, 1st and 3rd, 1st and 4th cols so on in a pandas df... until the last one.
Essentially I need to loop over 2 in the following command

newdf = df.iloc[:,[1,2]] # loop over the column index starting at 2 ending at the last col 

答案1

得分: 1

使用一个简单的循环:

for i in range(1, df.shape[1]):
    newdf = df.iloc[:, [0, i]]
    # 对newdf执行操作

请注意,在Python中索引从0开始,因此第一列是0,而不是1。如果你确实想要的是第二列和第三列(即第二个和第三个),那么请使用:

for i in range(2, df.shape[1]):
    newdf = df.iloc[:, [1, i]]
    # 对newdf执行操作
英文:

Use a simple loop:

for i in range(1, df.shape[1]):
    newdf = df.iloc[:, [0, i]]
    # do something with newdf

Note that indexing starts with 0 in python, so the first columns is 0, not 1. If you really meant columns 1 and 2 (second and third) in you example, then use:

for i in range(2, df.shape[1]):
    newdf = df.iloc[:, [1, i]]
    # do something with newdf

huangapple
  • 本文由 发表于 2023年6月8日 23:48:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76433627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定