Obtaining a pandas series by constructing its name as a string


I’m looking to construct a series name as a string and get its values for a given index, or set its value for a particular index. For example:

def getEntityValue(self, testCase, ent_order):
    if ent_order == 1:
        return self.testInputEnt1[testCase]
    elif ent_order == 2:
        return self.testInputEnt2[testCase]
    elif ent_order == 3:
        return self.testInputEnt3[testCase]

Or another one:

def setEntityValue(self, testCase, ent_order, value):
    if ent_order == 1:
        self.testResultEnt1[testCase] = value
    elif ent_order == 2:
        self.testResultEnt2[testCase] = value
    elif ent_order == 3:
        self.testResultEnt3[testCase] = value

Is there a simpler way of constructing this testInputEntX series in a better way? I’m well aware of the fact that it’s ideal to use other type of data structures where the values 1, 2, 3 can be used as another index and testInputEnt can be a list of series. But I will have to stick to these series for this application.

Asked By: Baykal



It could be refactored like:

def getEntityValue(self, testCase, ent_order):
    return getattr(self, f'testInputEnt{ent_order}')[testCase]
    #getattr(self, f'testInputEnt{ent_order}')[testCase] = value

But, why don’t you use a pandas.DataFrame instead of N pandas series? You can use DataFrame.at to get and update a cell

def getEntityValue(self, testCase, ent_order):
    return self.testResultEnt.at[ent_order, testCase]
    #self.testResultEnt.at[ent_order, testCase] = value
Answered By: ansev
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.