英文:
Add pre-defined value to DataFrame on each instance of matching index
问题
我正在尝试在df1中的每次名称和周匹配的情况下,将df中的相应值添加到df1中。
期望的结果是:
df1
Name Week Total
0 Frank Week 1 16
1 Frank Week 1 3
2 Frank Week 3 **36**
3 Frank Week 3 **9**
4 Frank Week 4 3
...
310 Daniel Week 2 50
311 Daniel Week 3 **58**
312 Daniel Week 4 78
313 Kevin Week 4 162
314 Kevin Week 4 46
英文:
I am trying to add the corresponding value from df to df1 for each time the name and week match in df1
df
Name Week Value
0 Frank Week 3 8.0
1 Bob Week 3 8.0
2 Bob Week 4 8.0
3 Elizabeth Week 3 4.0
4 Mario Week 2 1.5
5 Mario Week 3 2.5
6 Michelle Week 3 8.0
7 Michelle Week 4 1.0
8 Darwin Week 1 1.0
9 Darwin Week 2 0.5
10 Darwin Week 3 11.0
11 Collins Week 1 8.0
12 Collins Week 2 6.0
13 Collins Week 3 17.0
14 Collins Week 4 7.0
15 Alexis Week 1 1.5
16 Daniel Week 3 2.0
df1
Name Week Total
0 Frank Week 1 16
1 Frank Week 1 3
2 Frank Week 3 28
3 Frank Week 3 1
4 Frank Week 4 3
.. ... ... ...
310 Daniel Week 2 50
311 Daniel Week 3 56
312 Daniel Week 4 78
313 Kevin Week 4 162
314 Kevin Week 4 46
Expected:
df1
Name Week Total
0 Frank Week 1 16
1 Frank Week 1 3
2 Frank Week 3 **36**
3 Frank Week 3 **9**
4 Frank Week 4 3
.. ... ... ...
310 Daniel Week 2 50
311 Daniel Week 3 **58**
312 Daniel Week 4 78
313 Kevin Week 4 162
314 Kevin Week 4 46
答案1
得分: 0
out = (df1
.merge(df, how='left')
.assign(Total=lambda d: d['Total'].add(d.pop('Value'), fill_value=0))
)
输出:
Name Week Total
0 Frank Week 1 16.0
1 Frank Week 1 3.0
2 Frank Week 3 36.0
3 Frank Week 3 9.0
4 Frank Week 4 3.0
...
5 Daniel Week 2 50.0
6 Daniel Week 3 58.0
7 Daniel Week 4 78.0
8 Kevin Week 4 162.0
9 Kevin Week 4 46.0
英文:
out = (df1
.merge(df, how='left')
.assign(Total=lambda d: d['Total'].add(d.pop('Value'), fill_value=0))
)
Output:
Name Week Total
0 Frank Week 1 16.0
1 Frank Week 1 3.0
2 Frank Week 3 36.0
3 Frank Week 3 9.0
4 Frank Week 4 3.0
...
5 Daniel Week 2 50.0
6 Daniel Week 3 58.0
7 Daniel Week 4 78.0
8 Kevin Week 4 162.0
9 Kevin Week 4 46.0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论