Home > Net >  how to add elements of a list to elements of a row in pandas database
how to add elements of a list to elements of a row in pandas database

Time:03-19

i have this database called db in pandas

 index     win  loss  moneywin  moneyloss
player1     5     1       300        100
player2    10     5       650        150
player3    17     6      1100       1050
player11  1010   105     10650      10150
player23  1017   106    101100     101050

and i want to add the elements of list1 to the elements of db

list1 = [[player1,105,101,10300,10100],[player3,17,6,1100,1050]]

so the results would be db2

index     win   loss   moneywin  moneyloss
player1   110    102   10600      10200
player2    10     5     650         150
player3    34     12    2200       2100
player11  1010   105   10650      10150
player23  1017   106   101100    101050

how can i go about it?

CodePudding user response:

You can try with update after create the columns

s = pd.DataFrame(list1,columns=df.columns).set_index('index')
df = df.set_index('index')
df.update(s)
df
Out[890]: 
             win   loss  moneywin  moneyloss
index                                       
player1    105.0  101.0   10300.0    10100.0
player2     10.0    5.0     650.0      150.0
player3     17.0    6.0    1100.0     1050.0
player11  1010.0  105.0   10650.0    10150.0
player23  1017.0  106.0  101100.0   101050.0

CodePudding user response:

list1 = [['player1','105','101','10300','10100'],['player3','17','6','1100','1050']]

df.append(pd.DataFrame(list1,columns=df.columns)).sort_values(by=['index'])

     index   win loss moneywin moneyloss
0   player1     5    1      300       100
0   player1   105  101    10300     10100
3  player11  1010  105    10650     10150
1   player2    10    5      650       150
4  player23  1017  106   101100    101050
2   player3    17    6     1100      1050
1   player3    17    6     1100      1050

CodePudding user response:

Solution 1:

Create a dataframe from list1 then concat it with the given dataframe then group by index and aggregate the remaining columns using sum

df1 = pd.DataFrame(list1, columns=df.columns)
df_out = pd.concat([df, df1]).groupby('index', sort=False).sum()

Solution 2:

Create a dataframe from list1 then add it with the given dataframe using common index

df1 = pd.DataFrame(list1, columns=df.columns)
df_out = df.set_index('index').add(df1.set_index('index'), fill_value=0)

Result:

print(df_out)

           win  loss  moneywin  moneyloss
index                                    
player1    110   102     10600      10200
player2     10     5       650        150
player3     34    12      2200       2100
player11  1010   105     10650      10150
player23  1017   106    101100     101050
  • Related