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 halcon DrawRegion 提示错误
  • ¥15 FastAPI Uvicorn启动显示404
  • ¥15 centos7.9脚本,怎么排除特定的访问记录
  • ¥15 关于#Django#的问题:我的静态文件呢?
  • ¥15 关于CPLEX的问题,请专家解答
  • ¥15 cocos的点击事件 怎么穿透到 原生fragment上。
  • ¥20 基于相关估计的TDOA算法中的加权最小二乘拟合法matlab仿真
  • ¥20 基于相关估计的TDOA算法中的自适应加权广义互相关法。
  • ¥15 abaqus CAE 2024软件启动问题
  • ¥20 基于相关估计的TDOA算法中的局部互相关函数滤波matlab仿真