[英]How to sum single row to multiple rows in pandas dataframe using multiindex?
My dataframe with Quarter and Week as MultiIndex:我的 dataframe 与季度和周作为 MultiIndex:
Quarter Week X Y Z
Q1 Q1-W01 1 1 1
Q1-W02 2 2 2
Q1-W03 3 3 3
Q1-W04 4 4 4
Q2 Q2-W15 15 15 15
Q2-W16 16 16 16
Q2-W17 17 17 17
Q2-W18 18 18 18
I am trying to add the last row in Q1 (Q1-W04) to all the rows in Q2 (Q2-W15 through Q2-W18).我正在尝试将 Q1(Q1-W04)中的最后一行添加到 Q2(Q2-W15 到 Q2-W18)中的所有行中。 This is what I would like the dataframe to look like:
这就是我希望 dataframe 的样子:
Quarter Week X Y Z
Q1 Q1-W01 1 1 1
Q1-W02 2 2 2
Q1-W03 3 3 3
Q1-W04 4 4 4
Q2 Q2-W15 19 19 19
Q2-W16 20 20 20
Q2-W17 21 21 21
Q2-W18 22 22 22
When I try to only specify the level 0 index and sumthe specific row, all Q2 values go to NaN.当我尝试仅指定 0 级索引并对特定行求和时,所有 Q2 值 go 为 NaN。
df.loc['Q2'] += df.loc['Q1','Q1-W04']
Quarter Week X Y Z
Q1 Q1-W01 1 1 1
Q1-W02 2 2 2
Q1-W03 3 3 3
Q1-W04 4 4 4
Q2 Q2-W15 NaN NaN NaN
Q2-W16 NaN NaN NaN
Q2-W17 NaN NaN NaN
Q2-W18 NaN NaN NaN
I have figured out that if I specify both the level 0 and level 1 index, there is no problem.我发现如果我同时指定0级和1级索引,就没有问题。
df.loc['Q2','Q2-W15'] += df.loc['Q1','Q1-W04']
Quarter Week X Y Z
Q1 Q1-W01 1 1 1
Q1-W02 2 2 2
Q1-W03 3 3 3
Q1-W04 4 4 4
Q2 Q2-W15 19 19 19
Q2-W16 16 16 16
Q2-W17 17 17 17
Q2-W18 18 18 18
Is there a way to sum the specific row to all the rows within the Q2 Level 0 index without having to call out each row individually by its level 1 index?有没有办法将特定行与 Q2 0 级索引中的所有行相加,而不必通过其 1 级索引单独调用每一行?
Any insight/guidance would be greatly appreciated.任何见解/指导将不胜感激。
Thank you.谢谢你。
try this尝试这个
df.loc['Q2'] = (df.loc['Q2'] + df.loc['Q1', 'Q1-W04']).values.tolist()
df.loc returns a DataFrame, to set the value it looks for the list or array. df.loc 返回一个 DataFrame,设置它查找列表或数组的值。 Hence the above.
因此以上。
In your case we should remove the impact of index
在您的情况下,我们应该消除
index
的影响
df.loc['Q2','Q2-W15'] += df.loc['Q1','Q1-W04'].values
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.