Skip to content
Advertisement

How to do line level logic in Pandas

I have a table that has a bunch of columns and I need to create a new column based on the row type but the logic will be different for each type of row.

My data looks like this:

type field1 field2 field3 field4
1 a b c 17
2 e f g 20
3 i j k 100

the logic for rows of type 1 is concatenating field1, field2, field3

the logic for rows of type 2 is concatenating field2, field3, field4

the logic for rows of type 3 is squaring field4

The super important part I would like to avoid coding each type manually as there are hundreds of different types each with their own distinct logic that will change constantly. We enforce strict SDLC so deploying updates would be a nightmare. Ideally I would put this logic into a SQL table somewhere and then just somehow use the data in my pandas logic but I don’t know how to do that sort of thing.

Example:

JavaScript
Type Rule
1 field1+field2+field3
2 field2+field3+field4
3 field4**2
JavaScript
output
abc
fg20
10000

Advertisement

Answer

Merge the rules to the data and use eval method to evaluate rules according to type

JavaScript

enter image description here

Let me know if you have any questions.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement