如何使pandas dataframe在迭代时开始在不同的行迭代?



例如,如果您有一个包含1-10的数字的数据帧,如果它在迭代时发现值5,您希望它向前或向后走几行来执行一些必须逐行执行的操作,在这种情况下,为了保持简单,只需跳过下一行以恢复迭代,您如何做到这一点?

import pandas as pd
df=pd.DataFrame([1,2,3,4,5,6,7,8,9,10])
df.columns=['number']
start=0
for index, row in df.iloc[start:].iterrows():
print(index, row['number'])
if row['number']==5:
start=index+2

我得到:

0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10

但是我想让它给我:

0 1
1 2
2 3
3 4
4 5
6 7
7 8
8 9
9 10

通过你对你的问题的评论,看起来你的问题只是一个例子,找出一种方法来做你真正想要的,这看起来像XY问题。虽然我很确定你需要的东西可以用熊猫的方式来完成,它是矢量化的,快速的如果你想要一种通用的方式来循环,跳过行,返回或任何基于条件的你可以循环数据帧(会很慢,但ok)

i = 0
while True:
if i >= len(df):
break
row = df.iloc[i]
if condition1:
i += 10
elif condition2:
i + = 5
elif condition3:
i = max(0, i - 10)
else:
i += 1

找到等于5的值并移动遮罩,然后反转遮罩并保留所有其他行:

df = df[~df['number'].eq(5).shift(fill_value=False)]
>>> df
number
0       1
1       2
2       3
3       4
4       5
6       7
7       8
8       9
9      10

根据您的需要,您还可以使用一个简单的for循环与enumerate()方法:

for index, row in enumerate(df.number):
if index != 5:
print(index, row)
else:
continue

试试这个…

import pandas as pd
df=pd.DataFrame([1,2,3,4,5,6,7,8,9,10])
df.columns=['number']
start=0
for index, row in df.iloc[start:].iterrows():
if index==5:
# you can do your operation here
continue
else:
print(index, row['number'])

最新更新