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?
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
You can try with add
after create the columns
s = pd.DataFrame(list1,columns=df.columns).set_index('index')
df = df.set_index('index')
df = df.add(s,fill_value=0)
df
Out[108]:
win loss moneywin moneyloss
index
player1 110.0 102.0 10600.0 10200.0
player11 1010.0 105.0 10650.0 10150.0
player2 10.0 5.0 650.0 150.0
player23 1017.0 106.0 101100.0 101050.0
player3 34.0 12.0 2200.0 2100.0
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.