Lin_Cainiaoyige 2022-02-21 15:30 采纳率: 71.4%
浏览 35
已结题

Python Dataframe 根据其中一列判断 来增减字符

我有一个Dataframe
df = pd.DataFrame({'Category':['A','C','D','C,D','C,D','A,B,C','A,D','C','C','C','C','C','A,D','A,B,C','A,B,C','A,B,C','D','D','D','D','D'],
'Logic':['Add C','Add D','Add C','','','Del C','Add C','','','Del C','','Add E','Add C','','Upd B To F','','','','','Upd D To F','Add B']})

img

我想根据‘Logic’这列的提示 对 Category这列进行更改 达到以下结果

img


请各位帮助 谢谢!

  • 写回答

1条回答 默认 最新

  • heianduck 2022-02-21 16:05
    关注
    import pandas as pd
    df = pd.DataFrame({'Category':['A','C','D','C,D','C,D','A,B,C','A,D','C','C','C','C','C','A,D','A,B,C','A,B,C','A,B,C','D','D','D','D','D'],
    'Logic':['Add C','Add D','Add C','','','Del C','Add C','','','Del C','','Add E','Add C','','Upd B To F','','','','','Upd D To F','Add B']})
    
    def judge(rawStr, condition):
        if "Add" in condition:
            addValue = ",".join(i for i in condition.split(' ')[1:])
            newStr = rawStr +','+addValue
            return newStr
        elif "Del" in condition:
            delValue = condition.split(' ')[-1]
            if "," in rawStr:
                rawList = rawStr.split(',')
                rawList.remove(delValue)
                newStr = ",".join(i for i in rawList)
                return newStr
            else: 
                return ""
        elif "Upd" in condition:
            rawV = condition.split(' ')[1]
            newV = condition.split(' ')[3]
            newStr = rawStr.replace(rawV,newV)
            return newStr
        else:
            return rawStr
    df['Category_result'] = df.apply(lambda x: judge(x['Category'],x['Logic']),axis=1)
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 3月2日
  • 已采纳回答 2月22日
  • 创建了问题 2月21日

悬赏问题

  • ¥15 Index was outside the bounds of the array
  • ¥15 (标签-Python|关键词-数据类型)(相关搜索:数据类型)
  • ¥15 一个识别内容的自动化脚本程序
  • ¥15 anaconda虚拟python环境部署langchain-chatchat报错
  • ¥20 matlab有约束条件下的多元函数求最小值
  • ¥50 如何隐藏网页弹出框的url地址栏
  • ¥20 metropolis算法模拟二维ising模型来计算磁化强度,fortran
  • ¥15 uniapp-typescript-vue报错
  • ¥15 oracle强制关机以后报错01033
  • ¥15 给Chat with RTX添加语言模型时遇到问题