Skip to content
Merged

Dev #20

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/methods/dataframe/filtering/at.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,28 @@
* @returns {Object} - Object representing the selected row
*/
export const at = (df, index) => {
// Проверяем, что индекс является целым числом
// Check that index is an integer
if (!Number.isInteger(index)) {
throw new Error(
`Index must be an integer, got ${typeof index === 'number' ? index : typeof index}`,
);
}

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

const rows = df.toArray();

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

// Проверяем, что DataFrame не пустой
// Check that DataFrame is not empty
if (rows.length === 0) {
throw new Error('Cannot get row from empty DataFrame');
}
Expand Down
14 changes: 7 additions & 7 deletions src/methods/dataframe/filtering/filter.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/**
* Filters rows in a DataFrame based on a predicate function
*
* @param {DataFrame} df - Экземпляр DataFrame
* @param {Function} predicate - Функция-предикат для фильтрации строк
* @param {DataFrame} df - DataFrame instance
* @param {Function} predicate - Function to apply to each row
* @returns {DataFrame} - New DataFrame with filtered rows
*/
export const filter = (df, predicate) => {
Expand All @@ -16,12 +16,12 @@ export const filter = (df, predicate) => {
// Apply predicate to each row
const filteredRows = rows.filter(predicate);

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

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

// Если оригинальный массив был типизированным, создаем новый типизированный массив
// If the original array was typed, create a new typed array
if (
ArrayBuffer.isView(originalArray) &&
!(originalArray instanceof DataView)
Expand Down
28 changes: 14 additions & 14 deletions src/methods/dataframe/filtering/head.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,39 @@
/**
* Возвращает первые n строк DataFrame
* Returns the first n rows of a DataFrame
*
* @param {DataFrame} df - Экземпляр DataFrame
* @param {number} [n=5] - Количество строк для возврата
* @param {Object} [options] - Дополнительные опции
* @param {boolean} [options.print=false] - Опция для совместимости с другими библиотеками
* @returns {DataFrame} - Новый DataFrame с первыми n строками
* @param {DataFrame} df - DataFrame instance
* @param {number} [n=5] - Number of rows to return
* @param {Object} [options] - Additional options
* @param {boolean} [options.print=false] - Option for compatibility with other libraries
* @returns {DataFrame} - New DataFrame with the first n rows
*/
export const head = (df, n = 5, options = { print: false }) => {
// Проверка входных параметров
// Check input parameters
if (n <= 0) {
throw new Error('Number of rows must be a positive number');
}
if (!Number.isInteger(n)) {
throw new Error('Number of rows must be an integer');
}

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

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

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

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

return result;
};

/**
* Регистрирует метод head в прототипе DataFrame
* @param {Class} DataFrame - Класс DataFrame для расширения
* Registers the head method on DataFrame prototype
* @param {Class} DataFrame - DataFrame class to extend
*/
export const register = (DataFrame) => {
DataFrame.prototype.head = function (n, options) {
Expand Down
32 changes: 16 additions & 16 deletions src/methods/dataframe/filtering/iloc.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ export const iloc = (df, rowSelector, colSelector) => {
const allColumns = df.columns;
const rowCount = df.rowCount;

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

if (typeof rowSelector === 'number') {
// Один индекс строки
// One row index
const idx = rowSelector < 0 ? rowCount + rowSelector : rowSelector;
if (idx < 0 || idx >= rowCount) {
throw new Error(
Expand All @@ -24,7 +24,7 @@ export const iloc = (df, rowSelector, colSelector) => {
}
selectedIndices = [idx];
} else if (Array.isArray(rowSelector)) {
// Массив индексов строк
// Array of row indices
selectedIndices = rowSelector.map((idx) => {
const adjustedIdx = idx < 0 ? rowCount + idx : idx;
if (adjustedIdx < 0 || adjustedIdx >= rowCount) {
Expand All @@ -35,30 +35,30 @@ export const iloc = (df, rowSelector, colSelector) => {
return adjustedIdx;
});
} else if (typeof rowSelector === 'function') {
// Функция, возвращающая true/false для каждого индекса строки
// Function returning true/false for each row index
for (let i = 0; i < rowCount; i++) {
if (rowSelector(i)) {
selectedIndices.push(i);
}
}
} else if (rowSelector === undefined || rowSelector === null) {
// Выбираем все строки, если селектор не указан
// Select all rows if selector is not provided
selectedIndices = Array.from({ length: rowCount }, (_, i) => i);
} else {
throw new Error(
'Invalid row selector: must be a number, array of numbers, or function',
);
}

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

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

// Определяем индексы колонок для выбора
// Define column indices for selection
let selectedColumnIndices = [];
if (typeof colSelector === 'number') {
// Один индекс колонки
// One column index
const idx = colSelector < 0 ? allColumns.length + colSelector : colSelector;
if (idx < 0 || idx >= allColumns.length) {
throw new Error(
Expand All @@ -85,7 +85,7 @@ export const iloc = (df, rowSelector, colSelector) => {
}
selectedColumnIndices = [idx];
} else if (Array.isArray(colSelector)) {
// Массив индексов колонок
// Array of column indices
selectedColumnIndices = colSelector.map((idx) => {
const adjustedIdx = idx < 0 ? allColumns.length + idx : idx;
if (adjustedIdx < 0 || adjustedIdx >= allColumns.length) {
Expand All @@ -96,7 +96,7 @@ export const iloc = (df, rowSelector, colSelector) => {
return adjustedIdx;
});
} else if (typeof colSelector === 'function') {
// Функция, возвращающая true/false для каждого индекса колонки
// Function returning true/false for each column index
for (let i = 0; i < allColumns.length; i++) {
if (colSelector(i)) {
selectedColumnIndices.push(i);
Expand All @@ -108,10 +108,10 @@ export const iloc = (df, rowSelector, colSelector) => {
);
}

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

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

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

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