DataFrame.apply
Apply a function to each element or along a specified axis of a DataFrame.
danfo.DataFrame.apply(callable, options) [source]
Parameters
Type
Description
Default
callable
Function
Function to apply to each column or row
options
Object
axis: 0 or 1. If 0, compute the power column-wise, if 1, row-wise
{axis: 1}
Returns:
return DataFrame

Examples

Apply a function along default axis 1 (columns)

Note that the specified function passed to apply will be called with an array of the values across the specified axis.
Node
Browser
1
const dfd = require("danfojs-node")
2
3
let data = [[1, 2, 3], [4, 5, 6], [20, 30, 40], [39, 89, 78]]
4
let cols = ["A", "B", "C"]
5
let df = new dfd.DataFrame(data, { columns: cols })
6
7
function sum_vals(col) {
8
return col.reduce((a, b) => a + b, 0);
9
}
10
11
let df_new = df.apply(sum_vals, { axis: 1 })
12
df_new.print()
Copied!
1
Copied!
Output
1
╔═══╤═════╗
2
║ A │ 64 ║
3
╟───┼─────╢
4
║ B │ 126 ║
5
╟───┼─────╢
6
║ C │ 127 ║
7
╚═══╧═════╝
Copied!

Apply a function along axis 0 (row)

Node
Browser
1
const dfd = require("danfojs-node")
2
3
let data = [[1, 2, 3], [4, 5, 6], [20, 30, 40], [39, 89, 78]]
4
let cols = ["A", "B", "C"]
5
let df = new dfd.DataFrame(data, { columns: cols })
6
7
function sum_vals(col) {
8
return col.reduce((a, b) => a + b, 0);
9
}
10
11
let df_new = df.apply(sum_vals, { axis: 0 })
12
df_new.print()
13
Copied!
1
Copied!
Output
1
╔═══╤═════╗
2
║ 0 │ 6 ║
3
╟───┼─────╢
4
║ 1 │ 15 ║
5
╟───┼─────╢
6
║ 2 │ 90 ║
7
╟───┼─────╢
8
║ 3 │ 206 ║
9
╚═══╧═════╝
10
Copied!
Last modified 17d ago