Home > database >  Create new column in Python and use value from previous row
Create new column in Python and use value from previous row

Time:11-17

Im totally beginner in Python but I need to use the value from previous row. I read a lot of articles but I didn't catch the point :(

I have an Excel file with data, I sorted the data by 'D_i' column and here I found a problem. I need to add new column 'C_i' which contains in 1st row value from column 'Time', but in 2nd row and other ones I need to add the value from 2nd row from 'Time' column and value from 1st row in 'C_i' column.

Final layout should looks like this:

enter image description here

below is the 'code' (I got stuck at the beginning...)

import pandas as pd
import sympy as sp
import numpy as np

dane = pd.read_excel(r'/Users/artur/Desktop/Studia/V semestr/IO/Sprawozdanie1_dane.xlsx')
daneSortowane = dane.sort_values('Termin (D_i)')

CodePudding user response:

What you're trying to do is known as a cumulative sum. There is a built in function for this in pandas already, pd.cumsum()

From what I can gather from your question, adding the line:

daneSortowane['C_i'] = daneSortowane['Time'].cumsum()

Will add your C_i column as required.

  • Related