gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:23:06 24 4
gpt4 key购买 nike

我有一个数据框,

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']}]

结果数据框应该是,

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

“op_df”必须根据以下条件进行构建,

  • 条件 1:检查“details”列中是否存在“class”和“sec”,如果存在,则添加一个名为“subjects”的新列及其各自的值
  • 条件2:如果“details”列中不存在“class”和“sec”,则检查“class”是否匹配,如果匹配则添加一个名为“subjects”的新列及其各自的值
  • 如果条件1和条件2都不存在,则在“主题”列中添加默认值[0,0]

最佳答案

解决方案,如果需要首先通过 nextiter 两个条件匹配值,如果没有匹配,则添加默认值 [0, 0] :

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

关于python - Pandas : Compare the columns of a data frame and add a new column & value based on a condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58818418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com