pythoncsvmathmatrixmultiple-input

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 ,'})
w=int(inp[0])
h=int(inp[1])
        
print(w, "and", h)

df=pd.DataFrame()

for x in range(h):
    for i in range(w):
        m=input("Enter Data into Matrix at Position")
        print(x,",",i)
        df.loc[x,i]=m
        
print(df)

''' 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.


Solution

  • You can use sys.stdin.read() to read well... from stdin.

    import sys
    
    matrix = sys.stdin.read()
    
    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).