How do I iterate over the rows in dataframe and swap two adjacent rows and perform some operations on the new dataframe created after the swap?

192 views Asked by At
for i, rows in df.iterrows():
    x, y = df.iloc[rows].copy(), df.iloc[rows+1].copy()
    df.iloc[rows], df.iloc[rows+1] = y, x
    break

I get error on execution:

positional indexers are out-of-bounds`

My code in Spyder Complete code with operations to be performed after each swap

1

There are 1 answers

2
U13-Forward On

Use iloc with:

print(df.iloc[[a for b in zip(df.index[::2][::-1],df.index[1::2][::-1]) for a in b]][::-1])