0

Suppose I have the following dataframe:

df1 = {'Column_1':  ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
        'x': ['0', '1', '2', '3', '0', '1', '2', '3']}

df1 = pd.DataFrame (df1, columns = ['Column_1','x'])

df1

I want to create a new column called 'x!'. This is calculated by taking the value in the row 'x' and multiplying it be the row-1 of 'x!'. The value in the first row for 'x!' is 1. I need to calculation to reset when the value in 'Column_1' changes. The desired output would be the follwing:

df2 = {'Column_1':  ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
        'x': ['0', '1', '2', '3', '0', '1', '2', '3'],
        'x!': ['1', '1', '2', '6', '1', '1', '2', '6']}

df2 = pd.DataFrame (df2, columns = ['Column_1','x', 'x!'])

df2

Where 'x' is 3, 'x!' is 6 because 3 x 2 (x! row-1 = 2) is equal to 6.

How would I do this?

Thanks

Joe Smart
  • 41
  • 4

1 Answers1

0

Try this simple and clear approach:

let df1 = {'Column_1':  ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],'x': ['0', '1', '2', '3', '0', '1', '2', '3']}
let newX = ['1'];
    
    for(i=1; i<df1['x'].length; i++){
        let check = parseInt(df1.x[i],10)*parseInt(df1.x[i-1],10)
        if(check ===0){
            newX.push('1')
        }else{
            newX.push(check.toString())
        }
    }
    
    console.log(df1.x) //INITIAL ['0', '1', '2', '3', '0', '1', '2', '3']
    console.log(newX)  //RESULT  ['1', '1', '2', '6', '1', '1', '2', '6']

After that you can assign your new x! array:

df1['x!'] = newX

And apply to DataFrame

df2 = pd.DataFrame (df2, columns = Object.keys(df1))

I hope this solves your case. :)

George Gotsidis
  • 426
  • 4
  • 15