Pradeep
Pradeep

Reputation: 13

conditional with value from a particular cell in excel

I am trying to write a following matlab code in python:

function[x,y,z] = Testfunc(filename, newdata, a, b)
sheetname = 'Test1';
data = xlsread(filename, sheetname);
if data(1) == 1
    newdata(1,3) = data(2);
    newdata(1,4) = data(3);
    newdata(1,5) = data(4);
    newdata(1,6) = data(5)
else
....
....
....

It is very long function but this is the part where I am stuck and have no clue at all. This is what I have written so far in python:

import pandas as pd
def test_func(filepath, newdata, a, b):
    data = pd.read_excel(filepath, sheet_name = 'Test1')
    if data[0] == 1:

I am stuck here guys and I am also even not sure if the 'if' statement is right or not. I am looking for suggestions and help.

Info: excel sheet has 1 row and 13 columns, newdata is also a 2-D Matrix

Upvotes: 0

Views: 333

Answers (1)

Kevin K.
Kevin K.

Reputation: 1397

Try running that code and printing out your dataframe (print(data)). You will see that a dataframe is different than a MATLAB matrix. read_excel will try to infer your columns, so you will probably have no rows and just columns. To prevent pandas from reading the column use:

data = pd.read_excel(filepath, sheet_name='Test1', header=None)

Accessing data using an index will index that row. So your comparison is trying to find if the row is equal to 1 (which is never true in your case). To index a given cell, you must first index the row. To achieve what you are doing in MATLAB, use the iloc indexer on your dataframe: data.iloc[0,0]. What this does in accesses row 0, element 0. Your code should look like this:

import pandas as pd
def test_func(filepath, newdata, a, b):
    data = pd.read_excel(filepath, sheet_name = 'Test1')
    if data.iloc[0,0] == 1:
        newdata.iloc[0,2:6] = data.iloc[0,1:5]
        ....

I suggest you read up on indexing in pandas.

Upvotes: 2

Related Questions