简体   繁体   中英

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,

  • Condition 1: check if a "class" and "sec" exists in "details" column, if so add a new column named as "subjects" with its respective value
  • Condition 2:If a "class" and "sec" doesnt exist in "details" column, check if a "class" matches, if so add a new column named as "subjects" with its respective value
  • If both condition 1 and condition 2 doesnt exist, add the default value as [0,0] in "subjects" column

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM