Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas cumsum skip column

I am new to pandas and I can add to cumsum as

df.cumsum(axis=1)

   y0  y1  y2
0   2   3   4
1   2   2   3
2   0   0   0
3   1   2   3
   y0  y1  y2
0   2   5   9
1   2   4   7
2   0   0   0
3   1   3   6

But is there way to perform on only first 2 columns i.e. skip y2?

like image 522
user2661518 Avatar asked Oct 30 '25 19:10

user2661518


2 Answers

You can also use .loc to select only the columns you care about.

cols = ['y0', 'y1']
df.loc[:, cols] = df.loc[:, cols].cumsum(axis=1)

Output

   y0  y1  y2
0   2   5   4
1   2   4   3
2   0   0   0
3   1   3   3

loc is a flexible way to slice a DataFrame and in general follows the format:

.loc[row_labels, column_labels]

where an : can be used to indicate all rows, or all_columns.

like image 113
ALollz Avatar answered Nov 02 '25 22:11

ALollz


You need to exclude y2, find cumsum and concat y2 back.

pd.concat([df[['y0', 'y1']].cumsum(axis=1),df['y2']], axis=1)

Output:

    y0  y1  y2
0   2   5   4
1   2   4   3
2   0   0   0
3   1   3   3
like image 25
harvpan Avatar answered Nov 02 '25 23:11

harvpan