How to replace rows of a dataframe using rows of another dataframe based on indexes with pandas ?

Published: September 08, 2021

Tags: Python; Pandas; DataFrame;

DMCA.com Protection Status

Example of how to replace rows of a dataframe using rows of another dataframe based on indexes with pandas:

Create a first dataframe df

Let's create a first dataframe df

import pandas as pd
import numpy as np
import random

data = np.arange(1,101)

data = data.reshape(20,5)

df = pd.DataFrame(data=data,columns=['a','b','c','d','e'])

returns

         a   b   c   d    e
0    1   2   3   4    5
1    6   7   8   9   10
2   11  12  13  14   15
3   16  17  18  19   20
4   21  22  23  24   25
5   26  27  28  29   30
6   31  32  33  34   35
7   36  37  38  39   40
8   41  42  43  44   45
9   46  47  48  49   50
10  51  52  53  54   55
11  56  57  58  59   60
12  61  62  63  64   65
13  66  67  68  69   70
14  71  72  73  74   75
15  76  77  78  79   80
16  81  82  83  84   85
17  86  87  88  89   90
18  91  92  93  94   95
19  96  97  98  99  100

Create another dataframe df1

Let's create another dataframe:

data = np.random.randint(5, size=(4,5))

df1 = pd.DataFrame(data=data,columns=['a','b','c','d','e'],index=[0,7,12,5])

gives

        a  b  c  d  e
0   1  4  4  1  3
7   0  2  0  4  4
12  0  1  1  0  1
5   4  3  0  3  0

Replace rows of a dataframe using rows of another dataframe based on indexes

To replace rows of the dataframe df using rows from dataframe df1 a solution is to do:

df.loc[df1.index, :] = df1[:]

then df is:

         a   b   c   d    e
0    1   4   4   1    3
1    6   7   8   9   10
2   11  12  13  14   15
3   16  17  18  19   20
4   21  22  23  24   25
5    4   3   0   3    0
6   31  32  33  34   35
7    0   2   0   4    4
8   41  42  43  44   45
9   46  47  48  49   50
10  51  52  53  54   55
11  56  57  58  59   60
12   0   1   1   0    1
13  66  67  68  69   70
14  71  72  73  74   75
15  76  77  78  79   80
16  81  82  83  84   85
17  86  87  88  89   90
18  91  92  93  94   95
19  96  97  98  99  100

References