英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论