Skip to content

Commit 75d54e3

Browse files
authored
Merge pull request #20 from AlphaQuantJS/dev
Dev
2 parents 50161e4 + b19ead1 commit 75d54e3

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

65 files changed

+1303
-4737
lines changed

src/methods/dataframe/filtering/at.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,28 +6,28 @@
66
* @returns {Object} - Object representing the selected row
77
*/
88
export const at = (df, index) => {
9-
// Проверяем, что индекс является целым числом
9+
// Check that index is an integer
1010
if (!Number.isInteger(index)) {
1111
throw new Error(
1212
`Index must be an integer, got ${typeof index === 'number' ? index : typeof index}`,
1313
);
1414
}
1515

16-
// Проверяем, что индекс не отрицательный
16+
// Check that index is not negative
1717
if (index < 0) {
1818
throw new Error(`Negative indices are not supported, got ${index}`);
1919
}
2020

2121
const rows = df.toArray();
2222

23-
// Проверяем, что индекс находится в допустимом диапазоне
23+
// Check that index is in range
2424
if (index >= rows.length) {
2525
throw new Error(
2626
`Index ${index} is out of bounds for DataFrame with ${rows.length} rows`,
2727
);
2828
}
2929

30-
// Проверяем, что DataFrame не пустой
30+
// Check that DataFrame is not empty
3131
if (rows.length === 0) {
3232
throw new Error('Cannot get row from empty DataFrame');
3333
}

src/methods/dataframe/filtering/filter.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
/**
22
* Filters rows in a DataFrame based on a predicate function
33
*
4-
* @param {DataFrame} df - Экземпляр DataFrame
5-
* @param {Function} predicate - Функция-предикат для фильтрации строк
4+
* @param {DataFrame} df - DataFrame instance
5+
* @param {Function} predicate - Function to apply to each row
66
* @returns {DataFrame} - New DataFrame with filtered rows
77
*/
88
export const filter = (df, predicate) => {
@@ -16,12 +16,12 @@ export const filter = (df, predicate) => {
1616
// Apply predicate to each row
1717
const filteredRows = rows.filter(predicate);
1818

19-
// Если нет результатов, создаем пустой DataFrame с теми же колонками
19+
// If no results, create an empty DataFrame with the same columns
2020
if (filteredRows.length === 0) {
21-
// Создаем пустой объект с теми же колонками, но пустыми массивами
21+
// Create an empty object with the same columns, but empty arrays
2222
const emptyData = {};
2323
for (const col of df.columns) {
24-
// Сохраняем тип массива, если это типизированный массив
24+
// Save the array type, if it's a typed array
2525
const originalArray = df._columns[col].vector.__data;
2626
if (
2727
ArrayBuffer.isView(originalArray) &&
@@ -36,13 +36,13 @@ export const filter = (df, predicate) => {
3636
return new df.constructor(emptyData);
3737
}
3838

39-
// Создаем новый DataFrame с сохранением типов массивов
39+
// Create a new DataFrame with the same columns and types
4040
const filteredData = {};
4141
for (const col of df.columns) {
4242
const originalArray = df._columns[col].vector.__data;
4343
const values = filteredRows.map((row) => row[col]);
4444

45-
// Если оригинальный массив был типизированным, создаем новый типизированный массив
45+
// If the original array was typed, create a new typed array
4646
if (
4747
ArrayBuffer.isView(originalArray) &&
4848
!(originalArray instanceof DataView)

src/methods/dataframe/filtering/head.js

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,39 @@
11
/**
2-
* Возвращает первые n строк DataFrame
2+
* Returns the first n rows of a DataFrame
33
*
4-
* @param {DataFrame} df - Экземпляр DataFrame
5-
* @param {number} [n=5] - Количество строк для возврата
6-
* @param {Object} [options] - Дополнительные опции
7-
* @param {boolean} [options.print=false] - Опция для совместимости с другими библиотеками
8-
* @returns {DataFrame} - Новый DataFrame с первыми n строками
4+
* @param {DataFrame} df - DataFrame instance
5+
* @param {number} [n=5] - Number of rows to return
6+
* @param {Object} [options] - Additional options
7+
* @param {boolean} [options.print=false] - Option for compatibility with other libraries
8+
* @returns {DataFrame} - New DataFrame with the first n rows
99
*/
1010
export const head = (df, n = 5, options = { print: false }) => {
11-
// Проверка входных параметров
11+
// Check input parameters
1212
if (n <= 0) {
1313
throw new Error('Number of rows must be a positive number');
1414
}
1515
if (!Number.isInteger(n)) {
1616
throw new Error('Number of rows must be an integer');
1717
}
1818

19-
// Получаем данные из DataFrame
19+
// Get data from DataFrame
2020
const rows = df.toArray();
2121

22-
// Выбираем первые n строк (или все, если их меньше n)
22+
// Select the first n rows (or all if there are fewer than n)
2323
const selectedRows = rows.slice(0, n);
2424

25-
// Создаем новый DataFrame из выбранных строк
25+
// Create a new DataFrame from the selected rows
2626
const result = df.constructor.fromRows(selectedRows);
2727

28-
// Примечание: опция print сохранена для совместимости с API, но в текущей версии не используется
29-
// В будущем можно добавить метод print в DataFrame
28+
// Note: the print option is preserved for API compatibility, but is not used in the current version
29+
// In the future, we can add a print method to DataFrame
3030

3131
return result;
3232
};
3333

3434
/**
35-
* Регистрирует метод head в прототипе DataFrame
36-
* @param {Class} DataFrame - Класс DataFrame для расширения
35+
* Registers the head method on DataFrame prototype
36+
* @param {Class} DataFrame - DataFrame class to extend
3737
*/
3838
export const register = (DataFrame) => {
3939
DataFrame.prototype.head = function (n, options) {

src/methods/dataframe/filtering/iloc.js

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,11 @@ export const iloc = (df, rowSelector, colSelector) => {
1111
const allColumns = df.columns;
1212
const rowCount = df.rowCount;
1313

14-
// Определяем индексы строк для выбора
14+
// Define row indices for selection
1515
let selectedIndices = [];
1616

1717
if (typeof rowSelector === 'number') {
18-
// Один индекс строки
18+
// One row index
1919
const idx = rowSelector < 0 ? rowCount + rowSelector : rowSelector;
2020
if (idx < 0 || idx >= rowCount) {
2121
throw new Error(
@@ -24,7 +24,7 @@ export const iloc = (df, rowSelector, colSelector) => {
2424
}
2525
selectedIndices = [idx];
2626
} else if (Array.isArray(rowSelector)) {
27-
// Массив индексов строк
27+
// Array of row indices
2828
selectedIndices = rowSelector.map((idx) => {
2929
const adjustedIdx = idx < 0 ? rowCount + idx : idx;
3030
if (adjustedIdx < 0 || adjustedIdx >= rowCount) {
@@ -35,30 +35,30 @@ export const iloc = (df, rowSelector, colSelector) => {
3535
return adjustedIdx;
3636
});
3737
} else if (typeof rowSelector === 'function') {
38-
// Функция, возвращающая true/false для каждого индекса строки
38+
// Function returning true/false for each row index
3939
for (let i = 0; i < rowCount; i++) {
4040
if (rowSelector(i)) {
4141
selectedIndices.push(i);
4242
}
4343
}
4444
} else if (rowSelector === undefined || rowSelector === null) {
45-
// Выбираем все строки, если селектор не указан
45+
// Select all rows if selector is not provided
4646
selectedIndices = Array.from({ length: rowCount }, (_, i) => i);
4747
} else {
4848
throw new Error(
4949
'Invalid row selector: must be a number, array of numbers, or function',
5050
);
5151
}
5252

53-
// Если не указан селектор колонок, возвращаем все колонки для выбранных строк
53+
// If column selector is not provided, return all columns for selected rows
5454
if (colSelector === undefined || colSelector === null) {
55-
// Создаем новый DataFrame с сохранением типов массивов
55+
// Create a new DataFrame preserving typed arrays
5656
const filteredData = {};
5757
for (const col of allColumns) {
5858
const originalArray = df.col(col).toArray();
5959
const values = selectedIndices.map((index) => originalArray[index]);
6060

61-
// Если оригинальный массив был типизированным, создаем новый типизированный массив
61+
// If original array was typed, create a new typed array
6262
if (
6363
ArrayBuffer.isView(originalArray) &&
6464
!(originalArray instanceof DataView)
@@ -73,10 +73,10 @@ export const iloc = (df, rowSelector, colSelector) => {
7373
return new df.constructor(filteredData);
7474
}
7575

76-
// Определяем индексы колонок для выбора
76+
// Define column indices for selection
7777
let selectedColumnIndices = [];
7878
if (typeof colSelector === 'number') {
79-
// Один индекс колонки
79+
// One column index
8080
const idx = colSelector < 0 ? allColumns.length + colSelector : colSelector;
8181
if (idx < 0 || idx >= allColumns.length) {
8282
throw new Error(
@@ -85,7 +85,7 @@ export const iloc = (df, rowSelector, colSelector) => {
8585
}
8686
selectedColumnIndices = [idx];
8787
} else if (Array.isArray(colSelector)) {
88-
// Массив индексов колонок
88+
// Array of column indices
8989
selectedColumnIndices = colSelector.map((idx) => {
9090
const adjustedIdx = idx < 0 ? allColumns.length + idx : idx;
9191
if (adjustedIdx < 0 || adjustedIdx >= allColumns.length) {
@@ -96,7 +96,7 @@ export const iloc = (df, rowSelector, colSelector) => {
9696
return adjustedIdx;
9797
});
9898
} else if (typeof colSelector === 'function') {
99-
// Функция, возвращающая true/false для каждого индекса колонки
99+
// Function returning true/false for each column index
100100
for (let i = 0; i < allColumns.length; i++) {
101101
if (colSelector(i)) {
102102
selectedColumnIndices.push(i);
@@ -108,10 +108,10 @@ export const iloc = (df, rowSelector, colSelector) => {
108108
);
109109
}
110110

111-
// Получаем имена выбранных колонок
111+
// Get names of selected columns
112112
const selectedColumns = selectedColumnIndices.map((idx) => allColumns[idx]);
113113

114-
// Если выбрана только одна строка и одна колонка, возвращаем значение
114+
// If only one row and one column is selected, return the value
115115
if (
116116
selectedIndices.length === 1 &&
117117
selectedColumns.length === 1 &&
@@ -121,13 +121,13 @@ export const iloc = (df, rowSelector, colSelector) => {
121121
return df.col(selectedColumns[0]).toArray()[selectedIndices[0]];
122122
}
123123

124-
// Создаем новый DataFrame с сохранением типов массивов
124+
// Create a new DataFrame preserving typed arrays
125125
const filteredData = {};
126126
for (const col of selectedColumns) {
127127
const originalArray = df.col(col).toArray();
128128
const values = selectedIndices.map((index) => originalArray[index]);
129129

130-
// Если оригинальный массив был типизированным, создаем новый типизированный массив
130+
// If the original array was typed, create a new typed array
131131
if (
132132
ArrayBuffer.isView(originalArray) &&
133133
!(originalArray instanceof DataView)

0 commit comments

Comments
 (0)