Home > Blockchain >  Move a set of rows of a dataframe to the beginning
Move a set of rows of a dataframe to the beginning

Time:03-28

I want to move a set of dataframe rows to the beginning

The indexes of the corresponding rows are these ones:

indexes = [2188, 2163, 37, 47, 36, 41, 61, 1009, 40, 39, 123, 121, 2151, 19, 2, 8, 117, 205, 204]

So:

index 204 -> index 0
index 205 -> index 1
.
.
index 2188 -> index 18

At the moment I have this code that allows to move only one row:

def move_row(index):
    idx = [index]   [i for i in range(len(df)) if i != index]
    return df.iloc[idx].reset_index(drop=True)

CodePudding user response:

Here's an approach that reindexes the DataFrame based on using sets theory to create a new set list from indexes. This partially assumes that the indexes will be unique.

import pandas as pd

## sample DataFrame
d = {'col1': [0, 1, 2, 3, 4], 'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11]}
df = pd.DataFrame(data=d)

print(df)

##    col1  col2  col3
## 0     0     4     7
## 1     1     5     8
## 2     2     6    12
## 3     3     9     1
## 4     4     5    11

indexes = [3, 1]
new_idx = indexes   list(set(range(len(df))).difference(indexes))

df = df = df.iloc[new_idx].reset_index(drop = True)
print(df)

##    col1  col2  col3
## 0     3     9     1
## 1     1     5     8
## 2     0     4     7
## 3     2     6    12
## 4     4     5    11

CodePudding user response:

Finally I have followed these steps:

  1. Get desired subset of rows
  2. Remove those rows from the original dataframe
  3. Concatenate the desired rows with the rest of the dataframe

Code:

indexes = [2430, 2187, 2199, 37, 47, 36, 121, 41, 61, 1009, 40, 39, 123, 2151, 19, 2, 8, 117, 205, 204]
rows = df.iloc[indexes].reset_index(drop = True)
del_rows_df = df.drop(indexes).reset_index(drop = True)
new_df = pd.concat([rows, del_rows_df]).reset_index(drop = True)
  • Related