You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python Pandas根据指定列内容更新对应列值为1

问题描述

现有如下DataFrame:

description and keybenefits (14)brand_cooltouch (1711)brand_easylogic (1712)
Lorem Ipsum cooltouch Lorem Ipsum
Lorem Ipsum easylogic Lorem Ipsum
Lorem Ipsum Lorem Ipsum

需求:

  • 当列description and keybenefits (14)包含字符串'cooltouch'时,将列brand_cooltouch (1711)设为整数1;
  • 当列description and keybenefits (14)包含字符串'easylogic'时,将列brand_easylogic (1712)设为整数1。

期望输出:

description and keybenefits (14)brand_cooltouch (1711)brand_easylogic (1712)
Lorem Ipsum cooltouch Lorem Ipsum1
Lorem Ipsum Lorem Ipsum easylogic1
Lorem Ipsum Lorem Ipsum
解决方案

使用Pandas的str.contains()方法检测目标字符串,结合loc进行条件赋值即可实现需求:

import pandas as pd

# 构造示例DataFrame(如果已有现成DataFrame可跳过此步)
data = {
    'description and keybenefits (14)': [
        'Lorem Ipsum cooltouch Lorem Ipsum',
        'Lorem Ipsum easylogic Lorem Ipsum',
        'Lorem Ipsum Lorem Ipsum'
    ],
    'brand_cooltouch  (1711)': ['', '', ''],
    'brand_easylogic  (1712)': ['', '', '']
}
df = pd.DataFrame(data)

# 为匹配到cooltouch的行赋值1
df.loc[df['description and keybenefits (14)'].str.contains('cooltouch'), 'brand_cooltouch  (1711)'] = 1

# 为匹配到easylogic的行赋值1
df.loc[df['description and keybenefits (14)'].str.contains('easylogic'), 'brand_easylogic  (1712)'] = 1

# 若需要将自动生成的NaN转为空字符串(保持与原格式一致)
df = df.fillna('')

# 查看处理后的结果
print(df)

执行上述代码后,即可得到符合期望的DataFrame。

内容的提问来源于stack exchange,提问作者Isabella

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 10:50:36