Syntax to Reference Pandas Dataframe Columns using Enums

  pandas, python

I am importing a CSV file into a Pandas DataFrame object. I’ve created an Enum which I use to validate the quality of the imported CSV, and to reference the columns elsewhere in the application. A sample is below:

class FooProps(Enum):
    FOO = 'Foo'
    BAR = 'Bar Bar'

    def __str__(self):
        return self.value

data = ds.getFooProperties() # Imports CSV, Validates headers match enum

# Executes operation across Dataframe

someBigNumber = 10000
spam = someBigNumber/ data[str(FooProps.BAR)]  

I’m new to Python, but it seems counterintuitive that I need to reference the column by self-casting the enum as a string. Is there a more natural way to build the class such that I can index the columns by Class.Property without the extra syntax of invoking the cast? For example: spam = someBigNumber/ data[FooProps.BAR]

I thought about building an Abstract Class, but from what I understand those don’t exist… only abstract methods, which don’t really meet the requirement.

I also thought about making it a regular class, but then I have to declare an instance of that class and that also seems wrong.

Source: Python Questions

LEAVE A COMMENT