user2661518
user2661518

Reputation: 2745

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?

Upvotes: 4

Views: 1956

Answers (2)

ALollz
ALollz

Reputation: 59549

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.

Upvotes: 6

harpan
harpan

Reputation: 8631

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

Upvotes: 5

Related Questions