kstst
kstst

Reputation: 13

Python Pandas dataframe create a new column which contains the subtraction from another column

For now, I have something like:

date      item_number

2/28/2020 3.1

2/27/2020 3.9

2/26/2020 2.1

2/25/2020 1.9

I would like to have something like:

date      item_number delta

2/28/2020 3.1            0

2/27/2020 3.9          0.8

2/26/2020 2.1         -1.8

2/25/2020 1.9         -0.2

Any ideas on how to do it? I am a beginner for python and hope to have some suggestions. Thanks.

Upvotes: 1

Views: 66

Answers (2)

jezrael
jezrael

Reputation: 862901

Use Series.diff with replace missing value to 0:

df['item_number'] = pd.to_numeric(df['item_number'])
df['delta'] = df['item_number'].diff().fillna(0)
print (df)
        date  item_number  delta
0  2/28/2020          3.1    0.0
1  2/27/2020          3.9    0.8
2  2/26/2020          2.1   -1.8
3  2/25/2020          1.9   -0.2

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 148975

You can use shift, and fill the initial NaN with a 0:

df['delta'] = (df['item_number'] - df['item_number'].shift()).fillna(0.)

Upvotes: 1

Related Questions