GASでスプレッドシートの値をgetValuesで受け取ったら、二次元配列で取得されます。
この二次元配列から必要なデータを抽出していく時に、Pandasみたいに扱えると便利そうなので、クラスを自作しました。
class DataFrame {
constructor(df) {
this._head = df.slice(0, 1);
this._rows = df.slice(1, this.end);
}
get head() {
return this._head[0];
}
//列を削除。列は列名あるいは列のインデックスを詰めた配列で指定
drop(array, axis = 1) {
const head = this._head[0];
const index = typeof (array[0]) == "string" ? array.map(a => head.indexOf(a)) : array;
index.sort().reverse()
for (const i of index) {
this._head.forEach(h => h.splice(i, 1));
this._rows.forEach(row => row.splice(i, 1));
}
}
//指定した列だけ拾い上げる
select(array, axis = 1) {
const head = this._head[0];
const index = typeof (array[0]) == "string" ? array.map(a => head.indexOf(a)) : array;
this._head = this._head.map(head => head = head.filter((h, i) => index.includes(i)))
this._rows = this._rows.map(row => row = row.filter((r, i) => index.includes(i)))
}
//rename. columns={"変更したいカラム1":"変更後のカラム1", "変更したいカラム2":"変更後のカラム2"}
rename(columns) {
const head = this._head[0];
const pres = Object.keys(columns);
const posts = Object.values(columns);
this._head = new Array(head.map(h => {
const index = pres.indexOf(h);
return index > -1 ? posts[index] : h;
})
);
}
//算術演算子を用いて行を絞り込み。以下引数は全て文字列で指定
where(column, operator, value) {
const head = this._head[0];
const rows = this._rows;
const index = typeof (column) == "string" ? head.indexOf(column) : column;
let new_rows = [];
if(operator=="<") new_rows = rows.filter(row => row[index] < value);
if(operator=="<=")new_rows = rows.filter(row => row[index] <= value);
if(operator=="==")new_rows = rows.filter(row => row[index] == value);
if(operator==">=")new_rows = rows.filter(row => row[index] >= value);
if(operator==">") new_rows = rows.filter(row => row[index] > value);
if(operator=="!=")new_rows = rows.filter(row => row[index] != value);
this._rows = new_rows
}
}