Mahamutha M
Mahamutha M

Reputation: 1287

Pandas : Compare the columns of a data frame and add a new column & value based on a condition

I have a data frame which is,

ip_df:
     name class    sec    details
0    tom  I        a      [{'class':'I','sec':'a','subjects':['numbers','ethics']},{'class':'I','sec':'b','subjects':['numbers','moral-science']},{'class':'I','sec':'c','subjects':['moral-science','ethics']},{'class':'I','subjects':['numbers','ethics1']}]
1    sam  I        d      [{'class':'I','sec':'a','subjects':['numbers','ethics']},{'class':'I','sec':'b','subjects':['numbers','moral-science']},{'class':'I','sec':'c','subjects':['moral-science','ethics']},{'class':'I','subjects':['numbers','ethics1']}] 

and the resultant data frame is suppose to be,

op_df:
      name  class  sec   subjects
0     tom   I      a     ['numbers','ethics']
1     sam   I      d     ['numbers','ethics1']

The "op_df" has to be framed based on the following conditions,

Upvotes: 1

Views: 53

Answers (1)

jezrael
jezrael

Reputation: 862691

Solution if need first matched value by both conditions with next and iter trick for add default value [0, 0] if no matched:

final = []
for a, b, c in zip(df['class'], df['sec'], df['details']):
    out = []
    for x in c:
        m1 = x['class'] == a 
        if m1 and x.get('sec') == b:
            out.append(x['subjects'])
        elif m1 and 'sec' not in list(x.keys()):
            out.append(x['subjects'])
    final.append(next(iter(out), [0,0]))

df['subjects'] =  final

Upvotes: 2

Related Questions