0

I'm new to Python and I need a dynamic matrix that I can manipulate adding more columns and rows to it. I read about numpy.matrix, but I can't find a method in there that does what I mentioned above. It occurred to me to use lists but I want to know if there is a simpler way to do it or a better implementation.

Example of what I look for:

matrix.addrow ()
matrix.addcolumn ()
matrix.changeValue (0, 0, "$200")

Am I asking for too much? If so, any ideas of how to implement something like that? Thanks!

2 Answers 2

1

You can do all of that in numpy (np.concatenate for example) or native python (my_list.append()). Which one is more efficient will depend on what else your program will do: numpy will be probably less efficient if all you are doing is adding / changing values one at a time, or do a lot of column 'adding' or 'removing'. However if you do matrix or column operations, the overhead of adding new columns to a numpy array maybe offset by the vectorized computation speed offered by numpy. So pick which ever you prefer, and if speed is an issue, then you need to experiment yourself with both approaches...

-1

There are several ways to represent matrices in Python. You can use List of lists or numpy arrays. For example if you were to use numpy arrays

>>> import numpy as np
>>> a = np.array([[1,2,3], [2,3,4]])
>>> a
array([[1, 2, 3],
      [2, 3, 4]])

To add a row

 >>> np.vstack([a, [7,8,9]])
 array([[1, 2, 3],
       [2, 3, 4],
       [7, 8, 9]])

To add a column

 >>> np.hstack((a, [[7],[8]]))
 array([[1, 2, 3, 7],
        [2, 3, 4, 8]])
1
  • The OP seems to be aware of numy already. A list of lists will not behave like a matrix in almost any situation, including the one asked about here.
    – user2699
    Sep 22, 2017 at 16:56

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.