DataFrame.groupby
Group DataFrame using a mapper or by a Series of columns.
danfo.DataFrame.groupby(columns)
Parameters
Type
Description
Default
columns
Array
The names of a column(s) in the DataFrame to group by

Examples

Groupby a single column from a DataFrame

Node
Browser
1
const dfd = require("danfojs-node")
2
3
let data = [["Pear", 2, 3], ["Pear", 5, 6], ["Apple", 30, 40], ["Apple", 89, 78]]
4
let cols = ["A", "B", "C"]
5
6
let df = new dfd.DataFrame(data, { columns: cols })
7
let group_df = df.groupby(["A"])
8
console.log(group_df)
Copied!
1
// ouput
2
Groupby {
3
colDict: {
4
Pear: { A: [Array], B: [Array], C: [Array] },
5
Apple: { A: [Array], B: [Array], C: [Array] }
6
},
7
keyToValue: { Pear: [ 'Pear' ], Apple: [ 'Apple' ] },
8
keyCol: [ 'A' ],
9
data: [
10
[ 'Pear', 2, 3 ],
11
[ 'Pear', 5, 6 ],
12
[ 'Apple', 30, 40 ],
13
[ 'Apple', 89, 78 ]
14
],
15
columnName: [ 'A', 'B', 'C' ],
16
colDtype: [ 'string' ],
17
colIndex: [ 0 ]
18
}
Copied!
1
Copied!
A groupby operation will return a GroupBy class object. You can apply any of the following operation on the groupby result:
  1. 1.
    count
  2. 2.
    sum
  3. 3.
    std
  4. 4.
    var
  5. 5.
    mean
  6. 6.
    cumSum
  7. 7.
    cumMax
  8. 8.
    cumProd
  9. 9.
    cummin
  10. 10.
    max
  11. 11.
    min

Example of Groupby and apply a sum function

Node
1
const dfd = require("danfojs-node")
2
3
let data = [["Pear", 2, 3], ["Pear", 5, 6], ["Apple", 30, 40], ["Apple", 89, 78]]
4
let cols = ["A", "B", "C"]
5
let df = new dfd.DataFrame(data, { columns: cols })
6
let group_df = df.groupby(["A"]).sum()
7
8
group_df.print()
Copied!
1
╔════════════╤═══════════════════╤═══════════════════╤═══════════════════╗
2
║ │ A │ B_sum │ C_sum ║
3
╟────────────┼───────────────────┼───────────────────┼───────────────────╢
4
║ 0 │ Pear │ 7 │ 9 ║
5
╟────────────┼───────────────────┼───────────────────┼───────────────────╢
6
║ 1 │ Apple │ 119 │ 118 ║
7
╚════════════╧═══════════════════╧═══════════════════╧═══════════════════╝
Copied!

Groupby a two columns from a DataFrame

Node
Browser
1
const dfd = require("danfojs-node")
2
3
let data = [["Pear", 2, 3], ["Pear", 2, 6], ["Apple", 30, 40], ["Apple", 89, 78]]
4
let cols = ["A", "B", "C"]
5
let df = new dfd.DataFrame(data, { columns: cols })
6
let group_df = df.groupby(["A", "B"]).sum()
7
8
group_df.print()
Copied!
1
Copied!
1
╔════════════╤═══════════════════╤═══════════════════╤═══════════════════╗
2
║ │ A │ B │ C_sum ║
3
╟────────────┼───────────────────┼───────────────────┼───────────────────╢
4
║ 0 │ Pear │ 2 │ 9 ║
5
╟────────────┼───────────────────┼───────────────────┼───────────────────╢
6
║ 1 │ Apple │ 30 │ 40 ║
7
╟────────────┼───────────────────┼───────────────────┼───────────────────╢
8
║ 2 │ Apple │ 89 │ 78 ║
9
╚════════════╧═══════════════════╧═══════════════════╧═══════════════════╝
Copied!