Home > Back-end >  Add matrix with all similar value in one rows on pandas dataframe
Add matrix with all similar value in one rows on pandas dataframe

Time:07-01

Here's X

Id  Jakarta Bandung
1        10      40
2        20      50
3        30      60

Here's dataframe 'y`

Jakarta      Bandung
     11           12

And Xplusy

Id  Jakarta Bandung
1        21      52
2        31      62
3        41      72

How to code Xplusy?

CodePudding user response:

If Id is index use DataFrame.add witt select first row of Y for Series by DataFrame.iloc:

X = X.add(Y.iloc[0])
print (X)
    Jakarta  Bandung
Id                  
1        21       52
2        31       62
3        41       72

If Id is first column select all columns without first:

X.iloc[:, 1:] = X.iloc[:, 1:].add(Y.iloc[0])
print (X)
   Id  Jakarta  Bandung
0   1       21       52
1   2       31       62
2   3       41       72

Or get all columns same in both DataFrames by Index.intersection:

cols = X.columns.intersection(Y.columns)
X[cols] = X[cols].add(Y.iloc[0])
print (X)
   Id  Jakarta  Bandung
0   1       21       52
1   2       31       62
2   3       41       72

CodePudding user response:

You can slice y to Series using iloc[0] or squeeze and add:

If Id is the index:

x.add(y.iloc[0])
# or
x.add(y.squeeze())

Else, if Id is a column:

x.set_index('Id').add(y.iloc[0]).reset_index()

Or use reindex:

x.add(y.squeeze().reindex(x.columns, fill_value=0))

output:

   Id  Jakarta  Bandung
0   1       21       52
1   2       31       62
2   3       41       72
  • Related