python-3.x - 如果另一列的对应行包含某个子字符串,则在该列中分配一个字符串,否则为另一个字符串
问题描述
我有一个像这样的熊猫数据框
index | Creative Size | Business Model
1 | Something trueview |
2 | truviewhello |
3 | dunno |
4 | str |
5 | str |
我想编写一个代码,如果列中有“trueview”,将标签“CPV”分配给业务模型中的相应行,否则分配“CPM”。预期输出为:
index | Creative Size | Business Model
1 | Something trueview | CPV
2 | truviewhello | CPV
3 | dunno | CPM
4 | str | CPM
5 | str | CPM
我想出了这个:
count=0
for i in db_all['Creative Size']:
if 'trueview' in i:
db_all.loc[count, 'Business Model']='CPV'
else:
db_all.loc[count, 'Business Model']='CPM'
count = count+1
它有效,但速度很慢,有更好的主意吗?
解决方案
numpy.where
与 一起使用Series.str.contains
:
db_all['Business Model'] = np.where(db_all['Creative Size'].str.contains('trueview'),
'CPV',
'CPM')
推荐阅读
- vhdl - 将两个无符号(8 位)相加并将结果存储在 9 位无符号中时的错误结果
- qt - QML 更新 ListView 内 Item 的属性
- javascript - 传入组件的道具未定义
- linq - Linq 列表到字节数组
- python - Pygame KEYDOWN 箭头键导致玩家在移动过程中“卡住”
- python-3.x - 如何将自定义类的对象存储为 django 中的会话变量?
- python - 测试 django 脚本时打印语法错误
- android-source - Android AOSP make kernel menuconfig
- c++ - 无法在 Windows 凭据提供程序中使用非 ascii 字符(口音)
- java - BufferedReader 的 read(char[]) 是如何工作的?