-1

I would like to replace numeric column names in a DataFrame with their corresponding word names but still be able to sort the column names in order such that 'two' comes before 'eight'.

When learning Python, I came across a concept whereby we could say 'foo' means 3 and 'bar' means 8 such that later on in the program, 'foo' * 'bar' will be interpreted as 3*8 .

The solutions that I have come across so far (e.g this and this) involved explicitly converting the strings to integers before carrying out operations but I would like to assign numeric values to those strings such that python inherently knows what they represent however, I am no longer able to remember the name of the concept so my google search is not going smoothly. How can I do this?

Tambe Tabitha
  • 29
  • 1
  • 4
  • 3
    I’m voting to close this question because you need to find a tutorial, not do google searches. – thebjorn May 18 '22 at 01:52
  • 2
    You might be referring to assigning variables. For example, `foo=3` and `bar=8`, then you can do `foo*bar`. no strings involved. – jakub May 18 '22 at 01:59

1 Answers1

1

You can use a dict:

dictionary = {
   "foo": 1,
   "bar": 2
}
print(dictionary["foo"] * dictionary["bar"])

Or override the __mul__ magic method:

class Multi(object):
    def __init__(self, value):
        self.value = value

    def __mul__(self, other):
        return self.value * other.value

foo = Multi(3)
bar = Multi(8)
foo_bar = foo * bar
print(foo_bar)
mpioski
  • 28
  • 1
  • 6
  • The second example could drop the `Multi` wrapping and remove the `.value` extraction at the end and it would work just fine, no real benefit to the wrapping. It might even be what the OP is remembering, binding integers to names and using the names to do the math. – ShadowRanger May 18 '22 at 02:06