0

I have an integer n=3

I have to create a square matrix with below condition when matrix[row]=matrix[column] then 1 else 0

My plan is to create a table, insert n number of rows with all nulls initially and write an update with the above case statement in pandas sql.

Can anyone please help on this case to create a dataframe initially with n rows and n columns dynamically?

Thank you.

1 Answer 1

1

You can do something like this using numpy and pandas:

import numpy as np
import pandas as pd

def create_diagonal_matrix_of_size(n):
    if n > 0:
        d = np.diag(n * [1])
        df = pd.DataFrame(d)
        return df
    else:
        return pd.DataFrame()

print(create_diagonal_matrix_of_size(3))
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you I want to use only Pandas & SQL concepts if possible thank you for your answer & quick response.
Pandas uses numpy. So, if you are using Pandas, you have access to numpy already.
I am sorry for asking a dumb question, if i do it below : for i in range(0,n,1): ... a.append(n) for i in range(0,len(a),1): c.append([a]) Can i create a Dataframe on above & write a sql update .... with Spark sql probably... I am just curios on time complexity space.....

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.