简体   繁体   English

将不同行和列中的值求和

[英]sum values in different rows and columns dataframe python

My Data Frame 我的资料框

A B C D  
2 3 4 5  
1 4 5 6  
5 6 7 8  

How do I add values of different rows and different columns 如何添加不同行和不同列的值

  • Column A Row 2 with Column B row 1 列A第2行和列B第1行
  • Column A Row 3 with Column B row 2 A列第3行和B列第2行

Similarly for all rows 所有行都类似

If you only need do this with two columns (and I understand your question well), I think you can use the shift function. 如果您只需要用两列来完成此操作(并且我很好地理解了您的问题),我认为您可以使用shift函数。

Your data frame (pandas?) is something like: 您的数据框(熊猫?)类似于:

d = {'A': [2, 1, 5], 'B': [3, 4, 6], 'C': [4, 5, 7], 'D':[5, 6, 8]}
df = pd.DataFrame(data=d)

So, it's possible to create a new data frame with B column shifted: 因此,可以创建一个新的数据框,其中B列移位了:

df2 = df['B'].shift(1)

which gives: 这使:

0    NaN
1    3.0
2    4.0
Name: B, dtype: float64

and then, merge this new data with the previous df and, for example, sum the values: 然后,将此新数据与先前的df合并,例如,对值求和:

df = df.join(df2, rsuffix='shift')
df['out'] = df['A'] + df['Bshift']

The final output is in out column: 最终输出是在out列:

    A   B   C   D   Bshift  out
0   2   3   4   5   NaN     NaN
1   1   4   5   6   3.0     4.0
2   5   6   7   8   4.0     9.0

But it's only an intuition, I'm not sure about your question! 但这只是一种直觉,我不确定您的问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM