0

I have this dataframe (df) in python:

  Cumulative sales
0        12
1        28
2        56
3        87

I want to create a new column in which I whould have the the number of new sales (N-(N-1)) as below:

  Cumulative sales   New Sales
0        12             12
1        28             16
2        56             28
3        87             31
K. ossama
  • 403
  • 1
  • 4
  • 15
  • this is dupe of [this](https://stackoverflow.com/questions/13114512/calculating-difference-between-two-rows-in-python-pandas) or [this one](https://stackoverflow.com/questions/34846146/how-to-calculate-differences-between-consecutive-rows-in-pandas-data-frame) – Ben.T May 19 '20 at 23:50
  • 2
    Does this answer your question? [Calculating difference between two rows in Python / Pandas](https://stackoverflow.com/questions/13114512/calculating-difference-between-two-rows-in-python-pandas) – mechanical_meat May 19 '20 at 23:51
  • @Ben.T it worked! thanks man – K. ossama May 19 '20 at 23:58

2 Answers2

0

Do this:

df['New_sales'] = df['Cumlative_sales'].diff()
df.fillna(df.iloc[0]['Cumlative_sales'], inplace=True)
print(df)

Output:

   Cumlative_sales  New_sales
0               12       12.0
1               28       16.0
2               56       28.0
3               87       31.0
NYC Coder
  • 7,424
  • 2
  • 11
  • 24
0

You can do

df['new sale']=df.Cumulativesales.diff().fillna(df.Cumulativesales)
df
   Cumulativesales  new sale
0               12      12.0
1               28      16.0
2               56      28.0
3               87      31.0
BENY
  • 317,841
  • 20
  • 164
  • 234