Let's assume I have a pandas dataframe df as follow:
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 Col2
0 10 5
1 9 6
2 7 7
3 4 8
1 becomes 1 + 2 + 3 + 4 = 10
2 becomes 2 + 3 + 4 = 9
3 becomes 3 + 4 = 7
4 remains 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:
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
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.