Python 根据字符串条件将字符串列表运行到另一列,并将值替换为字符串中匹配的字符串

Python 根据字符串条件将字符串列表运行到另一列,并将值替换为字符串中匹配的字符串,python,pandas,Python,Pandas,我的表值看起来像 label title misc barbie song misc hello monster misc girls song misc barbie doll string_list=['barbie','girls'] 我的预期产出 label new_label misc barbie misc hello monster misc girls misc barbie

我的表值看起来像

label       title
misc        barbie song 
misc
hello       monster
misc        girls song
misc        barbie doll
string_list=['barbie','girls']

我的预期产出

label    new_label
misc     barbie
misc
hello    monster
misc     girls
misc     barbie
我想用“misc”处理标签,然后检查它是否有视频标题,如果有视频标题,我想检查相应的视频标题中是否出现任何字符串,或者用列表中匹配的字符串替换misc,或者创建一个名为new_label的新列,并将它们放在那里

如果杂项没有任何视频标题,则应为空 此外,除misc以外的任何标签都应保留其旧值

这在熊猫身上可以实现吗?
这个逻辑对我来说相当棘手

如果我理解正确,您只想对标签“misc”执行此操作,如果标签不包含列表字符串的任何值,则应为空,如果是这种情况,则下面的代码应执行此操作:

import pandas as pd

#your data
d = {'label':['misc', 'misc', 'hello', 'misc', 'misc'], 'title':['barbie sogn', '', 'monster', 'girls song', 'barbie doll']}
#create dataframe
df = pd.DataFrame(data = d)
#your strings list
string_list = ['barbie','girls']
#loop over slice of dataframe for label misc
for i, row in df.loc[df['label'] == 'misc'].iterrows():
    #define label and title
    label = df.at[i, 'label']
    title = df.at[i, 'title']
    #loop over list items
    for item in string_list:
        #check if string in list is in label
        if (item in title):
            #if yes then change it to item
            df['title'].loc[df.index == i] = item

#second loop to check if other titles that not in the list           
for i, row in df.loc[df['label'] == 'misc'].iterrows():
    label = df.at[i, 'label']
    title = df.at[i, 'title']
    #if value is not in list then set to blank
    if ((title != string_list[0]) & (title != string_list[1])):
        df['title'].loc[df.index == i] = ''      

我怎么能把“d”作为我的列名而不是把它们打出来呢?我不知道你的意思!!为什么要给d列命名?我这样做只是为了创建数据帧,我想你已经有了数据帧!它已经读到python了吗?如果不是,它是否在csv/txt文件中?那么您不需要前两行代码,因为您已经有了它,它们只是用来创建数据帧。您现在需要做的就是为现有数据帧运行其余代码。---------------------------------------------------------------------------------------TypeError Traceback(最近一次调用last)在37中,对于字符串列表中的项目:38#检查列表中的字符串是否在标签中-->39如果(标题中的项目):40#如果是,则将其更改为项目41合并报告['Video title']。loc[合并报告.index==i]=项类型错误:“float”类型的参数不是iterabley您不需要删除它们,只需使用df=df.fillna(“”),这将用空白替换它们,然后运行代码