Извлечь пересечение строк и столбцов за одну операцию [duplicate]

Math.sum (javascript) .... вид замещения оператора

.1 + .0001 + -.1 --> 0.00010000000000000286
Math.sum(.1 , .0001, -.1) --> 0.0001

Object.defineProperties(Math, {
    sign: {
        value: function (x) {
            return x ? x < 0 ? -1 : 1 : 0;
            }
        },
    precision: {
        value: function (value, precision, type) {
            var v = parseFloat(value), 
                p = Math.max(precision, 0) || 0, 
                t = type || 'round';
            return (Math[t](v * Math.pow(10, p)) / Math.pow(10, p)).toFixed(p);
        }
    },
    scientific_to_num: {  // this is from https://gist.github.com/jiggzson
        value: function (num) {
            //if the number is in scientific notation remove it
            if (/e/i.test(num)) {
                var zero = '0',
                        parts = String(num).toLowerCase().split('e'), //split into coeff and exponent
                        e = parts.pop(), //store the exponential part
                        l = Math.abs(e), //get the number of zeros
                        sign = e / l,
                        coeff_array = parts[0].split('.');
                if (sign === -1) {
                    num = zero + '.' + new Array(l).join(zero) + coeff_array.join('');
                } else {
                    var dec = coeff_array[1];
                    if (dec)
                        l = l - dec.length;
                    num = coeff_array.join('') + new Array(l + 1).join(zero);
                }
            }
            return num;
         }
     }
    get_precision: {
        value: function (number) {
            var arr = Math.scientific_to_num((number + "")).split(".");
            return arr[1] ? arr[1].length : 0;
        }
    },
    diff:{
        value: function(A,B){
            var prec = this.max(this.get_precision(A),this.get_precision(B));
            return +this.precision(A-B,prec);
        }
    },
    sum: {
        value: function () {
            var prec = 0, sum = 0;
            for (var i = 0; i < arguments.length; i++) {
                prec = this.max(prec, this.get_precision(arguments[i]));
                sum += +arguments[i]; // force float to convert strings to number
            }
            return Math.precision(sum, prec);
        }
    }
});

Идея состоит в том, чтобы вместо Math вместо Math использовать ошибки плавания

Math.diff(0.2, 0.11) == 0.09 // true
0.2 - 0.11 == 0.09 // false

также отмечают, что Math.diff и Math.sum автоматически определяют точность использования

. Math.sum принимает любое количество аргументов

5
задан bordeo 24 February 2016 в 17:39
поделиться

4 ответа

Вы можете просто использовать np.ix_ для такого вещания, например:

x_indexed = x[np.ix_(row_indices,col_indices)]

Пример прогона -

In [221]: x
Out[221]: 
array([[17, 39, 88, 14, 73, 58, 17, 78],
       [88, 92, 46, 67, 44, 81, 17, 67],
       [31, 70, 47, 90, 52, 15, 24, 22],
       [19, 59, 98, 19, 52, 95, 88, 65],
       [85, 76, 56, 72, 43, 79, 53, 37],
       [74, 46, 95, 27, 81, 97, 93, 69],
       [49, 46, 12, 83, 15, 63, 20, 79]])

In [222]: row_indices
Out[222]: [4, 2, 5, 4, 1]

In [223]: col_indices
Out[223]: [1, 2]

In [224]: np.ix_(row_indices,col_indices) # Broadcasting of indices
Out[224]: 
(array([[4],
        [2],
        [5],
        [4],
        [1]]), array([[1, 2]]))

In [225]: x[np.ix_(row_indices,col_indices)]
Out[225]: 
array([[76, 56],
       [70, 47],
       [46, 95],
       [76, 56],
       [92, 46]])

As , предложенный OP , это действует так же, как передача старой школы с версией 2D-массива row_indices, которая имеет свои элементы / индексы отправленные до axis=0 и, таким образом, создавая одномерную размерность в axis=1 и, таким образом, позволяя вещание с col_indices. Таким образом, у нас было бы альтернативное решение, подобное этому -

In [227]: x[np.array(row_indices)[:,None],col_indices]
Out[227]: 
array([[76, 56],
       [70, 47],
       [46, 95],
       [76, 56],
       [92, 46]])
10
ответ дан Community 26 August 2018 в 03:50
поделиться

Как насчет:

x[row_indices][:,col_indices]

Например,

x = np.random.random_integers(0,5,(5,5))
## array([[4, 3, 2, 5, 0],
##        [0, 3, 1, 4, 2],
##        [4, 2, 0, 0, 3],
##        [4, 5, 5, 5, 0],
##        [1, 1, 5, 0, 2]])

row_indices = [4,2]
col_indices = [1,2]
x[row_indices][:,col_indices]
## array([[1, 5],
##        [2, 0]])
3
ответ дан Julien Spronck 26 August 2018 в 03:50
поделиться

Я думаю, что вы пытаетесь выполнить одну из следующих операций (equlvalent):

x_does_work = x[row_indices,:][:,col_indices]
x_does_work = x[:,col_indices][row_indices,:]

Это фактически создаст подмножество из x только с выбранными строками, затем выберите столбцы из это, или наоборот во втором случае. Первый случай можно рассматривать как

x_does_work = (x[row_indices,:])[:,col_indices]
2
ответ дан Mad Physicist 26 August 2018 в 03:50
поделиться
import numpy as np
x = np.random.random_integers(0,5,(4,4))
x
array([[5, 3, 3, 2],
       [4, 3, 0, 0],
       [1, 4, 5, 3],
       [0, 4, 3, 4]])

# This indexes the elements 1,1 and 2,2 and 3,3
indexes = (np.array([1,2,3]),np.array([1,2,3]))
x[indexes]
# returns array([3, 5, 4])

Обратите внимание, что numpy имеет очень разные правила в зависимости от того, какие индексы вы используете. Поэтому индексирование нескольких элементов должно выполняться с помощью tuple из np.ndarray (см. Руководство по индексированию ).

Поэтому вам нужно только преобразовать ваши list в np.ndarray и он должен работать, как ожидалось.

2
ответ дан MSeifert 26 August 2018 в 03:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: