parse string as conditions to filter pandas dataframe

Viewed 1123

Hi I have a pandas dataframe, I have a column A.

data = pandas.DataFrame()
data['A']= [numpy.random.choice([1,2,3,4,5,6]) for i in range(10)]

I want to add a column B condition on A (when A =1 then B=0, when A>5 then B=1) instead of using:

data.loc[data['A']==1,'B']=0
data.loc[data['A']>5, 'B']=1

Here I want to create a function to do this given the condition as a dict: {'A=1':0,'A>5':1} so I could use add_column({'A=1':0,'A>5':1}, 'B') to do the code above. I am thinking it is tricky to deal with the operators, any good idea?

def add_column(condition_dict, NewColumnName):
    pass
1 Answers
Related