-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDataFrame.js
More file actions
203 lines (174 loc) · 6.44 KB
/
DataFrame.js
File metadata and controls
203 lines (174 loc) · 6.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// src/core/dataframe/DataFrame.js
import { Series } from './Series.js';
export class DataFrame {
/**
* @param {Record<string, Array|TypedArray>} data – source columns
* @param {object} [opts] – { preferArrow?: boolean }
*/
constructor(data = {}, opts = {}) {
/** @type {Record<string, Series>} */
this._columns = {};
/** @type {string[]} */
this._order = Object.keys(data);
for (const name of this._order) {
// Re-use Series or wrap raw data
this._columns[name] =
data[name] instanceof Series
? data[name]
: new Series(data[name], { name, ...opts });
}
Object.freeze(this._order);
/* -------------------------------------------------- *
* Internal helper (used by tests / plugins) *
* -------------------------------------------------- */
Object.defineProperty(this, 'frame', {
enumerable: false,
configurable: false,
value: {
/**
* low-level vector getter (internal)
* @param n
*/
getColumn: (n) => this._columns[n]?.vector,
},
});
}
/* ------------------------------------------------------------------ *
* Factory helpers *
* ------------------------------------------------------------------ */
static create = (cols, opts = {}) => new DataFrame(cols, opts);
static fromColumns = (cols, opts = {}) => new DataFrame(cols, opts);
static fromRows(rows = [], opts = {}) {
if (!rows.length) return new DataFrame({}, opts);
const cols = {};
for (const k of Object.keys(rows[0])) cols[k] = rows.map((r) => r[k]);
return new DataFrame(cols, opts);
}
static fromArrow(table) {
const cols = {};
for (const f of table.schema.fields)
cols[f.name] = table.getColumn(f.name).toArray();
return new DataFrame(cols, { preferArrow: true });
}
/* ------------------------------------------------------------------ *
* Export helpers *
* ------------------------------------------------------------------ */
toColumns() {
const out = {};
for (const n of this._order) out[n] = this._columns[n].toArray();
return out;
}
async toArrow() {
const { tableFromArrays } = await import('apache-arrow');
const arrays = {};
for (const n of this._order) {
const v = this._columns[n].vector;
arrays[n] = v._arrow ?? v._data; // ArrowVector | TypedArray
}
return tableFromArrays(arrays);
}
/* ------------------------------------------------------------------ *
* Accessors *
* ------------------------------------------------------------------ */
get rowCount() {
return this._columns[this._order[0]]?.length ?? 0;
}
get columns() {
return [...this._order];
}
col = (n) => this._columns[n];
sum = (n) => this.col(n).sum();
/**
* low-level vector getter
* @param n
*/
getVector = (n) => this._columns[n]?.vector;
/* ------------------------------------------------------------------ *
* Column-level helpers (select / drop / assign) *
* ------------------------------------------------------------------ */
select(names) {
const cols = {};
for (const n of names) cols[n] = this._columns[n].toArray();
return new DataFrame(cols);
}
drop(names) {
const keep = this.columns.filter((c) => !names.includes(c));
return this.select(keep);
}
assign(obj) {
const merged = this.toColumns();
for (const [k, v] of Object.entries(obj))
merged[k] = v instanceof Series ? v.toArray() : v;
return new DataFrame(merged);
}
/* ------------------------------------------------------------------ *
* Conversion to row array *
* ------------------------------------------------------------------ */
toArray() {
if (!this._order.length) return [];
const len = this.rowCount;
const rows = Array.from({ length: len }, (_, i) => {
const r = {};
for (const n of this._order) r[n] = this._columns[n].get(i);
return r;
});
return rows;
}
/* ------------------------------------------------------------------ *
* Lazy & meta *
* ------------------------------------------------------------------ */
lazy = () =>
import('../lazy/LazyFrame.js').then((m) => m.LazyFrame.fromDataFrame(this));
setMeta = (m) => ((this._meta = m), this);
getMeta = () => this._meta ?? {};
async optimizeFor(op) {
const { switchStorage } = await import('../strategy/storageStrategy.js');
return switchStorage(this, op);
}
/* ------------------------------------------------------------------ *
* Simple render helpers *
* ------------------------------------------------------------------ */
toHTML() {
const head = this.columns.map((n) => `<th>${n}</th>`).join('');
const body = this.toArray()
.map(
(row) =>
'<tr>' +
this.columns.map((n) => `<td>${row[n]}</td>`).join('') +
'</tr>',
)
.join('');
return `<table><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table>`;
}
toMarkdown() {
const header = '| ' + this.columns.join(' | ') + ' |';
const divider = '| ' + this.columns.map(() => '---').join(' | ') + ' |';
const rows = this.toArray().map(
(r) => '| ' + this.columns.map((n) => r[n]).join(' | ') + ' |',
);
return [header, divider, ...rows].join('\n');
}
/* ------------------------------------------------------------------ *
* Meta & storage helpers *
* ------------------------------------------------------------------ */
/**
* Set metadata for the DataFrame
* @param {any} m - Metadata to set
* @returns {DataFrame} - This DataFrame for chaining
*/
setMeta = (m) => ((this._meta = m), this);
/**
* Get metadata for the DataFrame
* @returns {any} - DataFrame metadata or empty object if not set
*/
getMeta = () => this._meta ?? {};
/**
* Optimize storage for operation
* @param {string} op - Operation to optimize for
* @returns {Promise<DataFrame>} - Optimized DataFrame
*/
async optimizeFor(op) {
const { switchStorage } = await import('../strategy/storageStrategy.js');
return switchStorage(this, op);
}
}