[英]Trying to create a new dataframe based on internal sums of a column from another dataframe using Python/pandas
Let's assume I have a pandas dataframe df as follow: 我们假设我有一个pandas数据帧df,如下所示:
df = DataFrame({'Col1':[1,2,3,4], 'Col2':[5,6,7,8]})
Col1 Col2
0 1 5
1 2 6
2 3 7
3 4 8
Is there a way for me to change a column into the sum of all the following elements in the column? 有没有办法让我将列更改为列中所有以下元素的总和?
For example for 'Col1' the result would be: 例如,对于'Col1',结果将是:
Col1 Col2
0 10 5
1 9 6
2 7 7
3 4 8
1 becomes 1 + 2 + 3 + 4 = 10 1变为1 + 2 + 3 + 4 = 10
2 becomes 2 + 3 + 4 = 9 2变为2 + 3 + 4 = 9
3 becomes 3 + 4 = 7 3变为3 + 4 = 7
4 remains 4 4仍然是4
If this is possible, is there a way for me to specify a cut off index after which this behavior would take place? 如果这是可能的,有没有办法让我指定一个截止索引,之后会发生这种行为? For example if the cut off index would be the key 1, the result would be:
例如,如果截止索引是键1,结果将是:
Col1 Col2
0 1 5
1 2 6
2 7 7
3 4 8
I am thinking there is no other way than using loops to do this, but I thought there might be a way using vectorized calculations. 我在想除了使用循环之外别无他法,但我认为可能有一种方法可以使用矢量化计算。
Thanks heaps 谢谢堆
Yes, you could use loop but very cheap one: 是的,你可以使用循环但非常便宜的:
def sum_col(column,start=0):
l = len(column)
return [column.values[i:].sum() for i in range(start,l)]
And usage: 用法:
data['Col1'] = sum_col(data['Col1'],0)
Here is one way to avoid loop. 这是一种避免循环的方法。
import pandas as pd
your_df = pd.DataFrame({'Col1':[1,2,3,4], 'Col2':[5,6,7,8]})
def your_func(df, column, cutoff):
# do cumsum and flip over
x = df[column][::-1].cumsum()[::-1]
df[column][df.index > cutoff] = x[x.index > cutoff]
return df
# to use it
your_func(your_df, column='Col1', cutoff=1)
Out[68]:
Col1 Col2
0 1 5
1 2 6
2 7 7
3 4 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.