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
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.
15 Python Array Examples – Declare, Append, Index, Remove, Count.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With