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 pdimport numpy as npimport randomdata = 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 e0 1 2 3 4 51 6 7 8 9 102 11 12 13 14 153 16 17 18 19 204 21 22 23 24 255 26 27 28 29 306 31 32 33 34 357 36 37 38 39 408 41 42 43 44 459 46 47 48 49 5010 51 52 53 54 5511 56 57 58 59 6012 61 62 63 64 6513 66 67 68 69 7014 71 72 73 74 7515 76 77 78 79 8016 81 82 83 84 8517 86 87 88 89 9018 91 92 93 94 9519 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 e0 1 4 4 1 37 0 2 0 4 412 0 1 1 0 15 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 e0 1 4 4 1 31 6 7 8 9 102 11 12 13 14 153 16 17 18 19 204 21 22 23 24 255 4 3 0 3 06 31 32 33 34 357 0 2 0 4 48 41 42 43 44 459 46 47 48 49 5010 51 52 53 54 5511 56 57 58 59 6012 0 1 1 0 113 66 67 68 69 7014 71 72 73 74 7515 76 77 78 79 8016 81 82 83 84 8517 86 87 88 89 9018 91 92 93 94 9519 96 97 98 99 100
