Home > Enterprise >  Problem importing matrix in Python from Excel and maybe some problems with if elif statments
Problem importing matrix in Python from Excel and maybe some problems with if elif statments

Time:09-23

I'm trying running this code with some problems to solve. I'm at first trying inserting "BOD" as the name of the output and "6" as the number of input parameters.

    import os
    import numpy as np
    import pandas as pd
    from pandas import ExcelWriter
    from numpy import *
    
    OutputName = input('please enter the name of the output (BOD,COD,TSS)');
    InputNum = input('please enter the number of input parameters (6 or 12) = ');
    file_name = 'biowin_withMalfunction.xlsx'
    
    if OutputName == 'BOD':
               Output_num=1
               if InputNum == 6:
                  Data = pd.read_excel(open(r'C:\Users\Elisa\test_conv_Fatone\biowin_withMalfunction.xlsx', 'rb'), sheet_name='ANN full data for BOD_6Params')
                  print (Data)
               elif InputNum ==12:
                Data = pd.read_excel(open(r'C:\Users\Elisa\test_conv_Fatone\biowin_withMalfunction.xlsx', 'rb'), sheet_name='ANN full data for BOD')
    elif OutputName == 'COD':
               Output_num=2
               if InputNum == 6:
                Data = pd.read_excel(open(r'C:\Users\Elisa\test_conv_Fatone\biowin_withMalfunction.xlsx', 'rb'), sheet_name='ANN full data for COD_6ParamsD')
               elif InputNum ==12:
                Data = pd.read_excel(open(r'C:\Users\Elisa\test_conv_Fatone\biowin_withMalfunction.xlsx', 'rb'), sheet_name='ANN full data for COD')
    else:
               Output_num=3
               if InputNum == 6:
                Data = pd.read_excel(open(r'C:\Users\Elisa\test_conv_Fatone\biowin_withMalfunction.xlsx', 'rb'), sheet_name='ANN full data for TSS_6Params')
               elif InputNum ==12:
                Data = pd.read_excel(file_name, sheet_name="ANN full data for TSS")
    
    index = Output_num -3;
    X = Data[0:end-2,0:end]

the error is:

    Traceback (most recent call last):
      File "C:\Users\Elisa\test_conv\ANN_Converted.py", line 42, in <module>
        X = Data[0:end-2,0:end]
    NameError: name 'Data' is not defined

It seems that the variable Data is not created with pd.reading, in fact, if I try print(Data) it does not exist. Can anybody help me finding the problem/problems? Can I share the input excel file? How?

CodePudding user response:

Think about your conditions. What happens if every individual test is False? What happens if all your tests are False ?

There is a path through your decision tree in which no file is opened. This is currently obtaining, so Data doesn't exist, as you determined.

In this case the problem is likely that input() returns a string, whereas you are testing for an integer.

Thus either test for strings:

if inputNum == "5"

or cast inputNum to an int:

inputNum = int(inputNum)

before you do any testing.

  • Related