如何使用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 Ipsum | 1 | |
| Lorem Ipsum Lorem Ipsum easylogic | 1 | |
| 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
相关产品推荐
相关产品推荐

