首页 > 解决方案 > 如果另一列的对应行包含某个子字符串,则在该列中分配一个字符串,否则为另一个字符串

问题描述

我有一个像这样的熊猫数据框

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

它有效,但速度很慢,有更好的主意吗?

标签: python-3.xpandasdataframe

解决方案


numpy.where与 一起使用Series.str.contains

db_all['Business Model'] = np.where(db_all['Creative Size'].str.contains('trueview'), 
                                    'CPV', 
                                    'CPM')

推荐阅读