Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What sort of Python array would this be? Does it already exist in Python?

I have a numpy array:

m = array([[4, 0, 9, 0],
          [0, 7, 0, 0],
          [0, 0, 0, 0],
          [0, 0, 0, 5]])

The 4 columns of m are labelled:

c = array([ 10, 20, 30, 40])

I want to be able to slice an object o such that:

o.vals[0,:] = array([4, 9])
o.vals[1,:] = array([7,])
o.vals[2,:] = array([])
o.vals[3,:] = array([5])
o.cols[0,:] = array([10, 30] )# the non-zero column labels from row 0
o.cols[1,:] = array([20,])
o.cols[2,:] = array([])
o.cols[3,:] = array([40])

Is there an existing Python object that would let me do this?

I have looked at Scipy Sparse Matrices, but it isn't quite what I am looking for.

AN UPDATE on 17th August 2015: I have had a play around with some ideas and came up with this, which is almost the same as what I described last week:

  • https://github.com/jsphon/NumericalFunctions/blob/master/jagged_array/JaggedKeyValueArray.rst

  • https://github.com/jsphon/NumericalFunctions/blob/master/jagged_array/jagged_key_value_array.py

like image 651
Ginger Avatar asked Aug 11 '15 07:08

Ginger


People also ask

How do I check if an array exists in Python?

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.

How many types of arrays are there in Python?

15 Python Array Examples – Declare, Append, Index, Remove, Count.


1 Answers

You can get close to what you want by defining a class to contain m and c:

import numpy as np

class O(object):
    def __init__(self, m, c):
        self.m, self.c = m, c

    def vals(self, i):
        return self.m[i][self.m[i]!=0]

    def cols(self, i):
        return self.c[self.m[i]!=0]


m = np.array([[4, 0, 9, 0],
          [0, 7, 0, 0],
          [0, 0, 0, 0],
          [0, 0, 0, 5]])

c = np.array([ 10, 20, 30, 40])

o = O(m, c)

for i in range(4):
    print 'o.vals({0:d}) = {1}'.format(i, o.vals(i))
for i in range(4):
    print 'o.cols({0:d}) = {1}'.format(i, o.cols(i))

Returns:

o.vals(0) = [4 9]
o.vals(1) = [7]
o.vals(2) = []
o.vals(3) = [5]
o.cols(0) = [10 30]
o.cols(1) = [20]
o.cols(2) = []
o.cols(3) = [40]

(It might be easier to use the indexing, m[i][m[i]!=0 and c[m[i]!=0] directly, though.)

like image 76
xnx Avatar answered Oct 26 '22 08:10

xnx