Perform math operations inside Python switch case equivalent

564 Views Asked by At

I am trying to simplify an if-elif-else block in Python with a Switch case equivalent. But I am having issues trying to perform math operations inside the switch case dictionary

I am performing this code inside a FOR loop that is running through a pandas dataframe. Basically doing some math based on a condition.

Sample Dataframe:

10889  103.579   89.160  2.98   2.1154     NaN   in 0.48  0.20   15.0
10890  103.859   89.133  2.98   2.1266     NaN   out 0.48  0.20   15.0
10891  104.067   89.133  2.98   2.1349     NaN   out 0.48  0.20   15.0
10892  106.867   91.933  2.98    2.293     NaN   out 0.48  0.20   15.0
10893  106.867   91.859  2.98   2.2959     NaN   sol 0.48  0.20   15.0
10894  106.840   91.579  2.98   2.3072     NaN   sol 0.48  0.20   15.0
10895  106.785   91.302  2.98   2.3184     NaN   sol 0.48  0.20   15.0
10896  106.728   91.115  2.98   2.3263     NaN   text 0.48  0.20   15.0
10897  104.885   89.272  2.98   2.4303     NaN   text 0.48  0.20   15.0
10898  104.885   89.272  2.98        0     NaN   mid 0.48  0.20   15.0

Current piece of code:

       if self.newdataframe.iloc[i]['FT'] in ('in', 'out'):
            self.ext_out += edis
       elif self.newdataframe.iloc[i]['FT'] == 'sol':
            self.ext_sol += edis
       elif self.newdataframe.iloc[i]['FT'] == 'mid':
            self.ext_mid += edis
       elif self.newdataframe.iloc[i]['FT'] == 'text':
            self.ext_text += edis
       else:
            self.ext_other += edis

Converting this to a switch case.. Here is my attempt. The code looks something like this but it is obviously throwing errors

newdict = { 'in': self.ext_out += edis,
'out': self.ext_out += edis,
'sol': self.ext_sol += edis,
'mid': self.ext_mid += edis,
'text': self.ext_text += edis}

newdict[self.newdataframe.iloc[i]['FT']]

I tried using Lambda functions but that seems to cause issue with the self. variables. Any pointers or guidance, sample examples are much appreciated

2

There are 2 best solutions below

1
On BEST ANSWER

It would probably be better if self.ext were a dictionary with keys out, sol, etc, instead of separate attributes for each. As is, you can use setattr with an appropriate dict.

d = {x: x for x in ['out', 'mid', 'sol', 'text']}
d['in'] = 'out'
x = 'ext_' + d.get(self.newdataframe.iloc[i]['FT'], 'other')
setattr(self, x, getattr(self, x) + edis)

The better approach:

self.ext[d.get(self.newdataframe.iloc[i]['FT'], 'other')] += edis
0
On

What you call a "switch case equivalent" is called a dictionary. A dictionary is a data structure for key-value pairs. A dictionary will not execute code in the same way as the if...else chain. You can only store values in a dictionary. These values may be functions since functions in python are first-class citizens. But this doesn't really lend itself to a simple solution in python. The original if...else chain is perfectly acceptable.