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

2024/10/7 0:25:16

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]=mprint(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.

Answer

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

import sysmatrix = 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).

https://en.xdnf.cn/q/118887.html

Related Q&A

Cannot create environment in anaconda, update conda , install packages

CondaHTTPError: HTTP 000 CONNECTION FAILED for url https://repo.anaconda.com/pkgs/free/win-64/repodata.json.bz2 Elapsed: -An HTTP error occurred when trying to retrieve this URL. HTTP errors are often …

Inverted Triangle in Python-not running

I have to create a program to print an inverted triangle in python. When I was running it in Sublime Text 3 it did not run. By that, I mean that it did not even print a syntax error. def triangle():x =…

How to do Data profile to a table using pandas_profiling

When Im trying to do data profiling one sql server table by using pandas_profiling throwing an error like An attempt has been made to start a new process before thecurrent process has finished its boot…

Python replace line by index number

Is it possible in Python to replace the content of a line in a file by its index number?Would something like a line.replace to do this procedure?

print/list only 5 entries from OS.Walk in python

My Goal - To list only 5 entries when using OS walk. So far I have only been able to get a list of everything that I find using OS.Walk or only list one entry. (By using the return function) My code: i…

Numpy vectorisation of python object array

Just a short question that I cant find the answer to before i head off for the day,When i do something like this:v1 = float_list_python = ... # <some list of floats> v2 = float_array_NumPy = ... …

Python user must only enter float numbers

I am trying to find out how to make it so the user [only enters numbers <0] and [no letters] allowed. Can someone show me how I would set this up. I have tried to set up try/catch blocks but I keep …

Django 1.7: some_name() takes exactly 2 arguments (1 given)

this is my view.pyfrom django.http import HttpResponse import datetime def current_datetime(request):now = datetime.datetime.now()html = "<html><body>It is now %s.</body></htm…

Solving Linear equations with constraint in Python

I have a system of linear equations with some constraints. I would appreciate it if someone could help me solving this system of equations in Python.

systemd service keep giving me error when start or get status

I have a python application and I need it to be run as a service, I tried many methods and I was advised to make it as systemd service I searched and tried some code here is my unit code [Unit] Descrip…