How to take a whole matrix as a input in Python?


I want to take a whole matrix as an input in Python and store it in a dataframe. Pandas can do it automatically with read_csv function but it requires a CSV file. I want to input/copy-paste a matrix directly at the input, without specifying its height or width and intelligently separate the rows and columns using Line Break as a separator and store it in a dataframe. Looked up the read_csv source code but it all went over my head. your help will be appreciated.

What’s a Matrix: Basically a Mathematical table or Dataframe which Looks something like this…
matrix in a notepad

What I have Come up with up until now is the same old thingy:

inp=input("Enter the Size of Your Matrix: ")
inp=inp.translate({ord(i): None for i in 'x ,'})
print(w, "and", h)


for x in range(h):
    for i in range(w):
        m=input("Enter Data into Matrix at Position")

What I want to do is if I have a matrix copied like like the one shown above, I can use it directly as a input to store in a dataframe, and I want the code to be intelligent enough to break up the lines automatically wherever there is a line Break.

Asked By: Rishit Chakraborty



You can use to read well… from stdin.

import sys

matrix =

matrix = matrix.strip().split('n')
matrix = [row.split(' ') for row in matrix]

Now you get something like [['2', '3', '4'], ['6', '7', '8'], ['4', '1', '1']] and you can convert it to your desired format.

Note that once you have pasted your matrix, you still need to tell the system to stop reading. In Windows you can do it with Ctrl + Z followed by Enter. In Linux with Ctrl + D (no enter afterwards).

Answered By: Ignatius Reilly