dataframe js calculation in each row

1k views Asked by At

I am new to nodejs and looking to loop through each row and subtract previous row cell using dataframe-js library.

const columns = ["x","y","gap"];

const df= new DataFrame(dict,columns);

df.sortBy(['y'], true);

df.map(row => row.set('gap', row.get('y') - row.get('y')-1));
2

There are 2 answers

0
Tony On

You could do it like this:

var df = df.withColumn('gap', row => row.get('y') - row.get('x'));

Full code:

var df = new dfjs.DataFrame({'x': [1, 2, 3], 'y': [6, 5, 4]}, ['x', 'y'])
var df = df.withColumn('gap', row => row.get('y') - row.get('x'));  

df.show()

Produces:

| x         | y         | gap       |
------------------------------------
| 1         | 6         | 5         |
| 2         | 5         | 3         |
| 3         | 4         | 1         |
1
xtr On

You didn't really ask question, if you want to know how to access the previous element within Array.map() it's quite easy Array.map() passes the index of the current element as 2nd paramater and the array as 3rd so you could do something

df.map((row,i,rows) => {
   row.set('gap', row.get('y') - (i>0?rows[i-1].get('y'):0))
})

on another note unless you are returning something you should use

df.forEach() instead of df.map()