Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用列表标记dataframe列_Python_Pandas - Fatal编程技术网

Python 使用列表标记dataframe列

Python 使用列表标记dataframe列,python,pandas,Python,Pandas,我有一个数据框列text text 'a red apple' 'the apple is sweet' 'a yellow banana' 'a green melon' 我想创建另一个列term,将它与一个列表['apple'、'banana'、wall'] for term in the_list: df['term'] = bf['text'].apply(lambda x: term if term in x else 'None') 我得到的结果 text

我有一个数据框列
text

text
'a red apple'
'the apple is sweet'
'a yellow banana'
'a green melon'
我想创建另一个列
term
,将它与一个列表
['apple'、'banana'、wall']

for term in the_list:
    df['term'] = bf['text'].apply(lambda x: term if term in x else 'None')
我得到的结果

text                 term  
'a red apple'        None
'the apple is sweet' None
'a yellow banana'    None
'a green melon'      melon
然而,我预料会是这样

text                 term  
'a red apple'        apple
'the apple is sweet' apple
'a yellow banana'    banana
'a green melon'      melon

我感觉可能是因为我使用了一个列表,但我不知道如何在lambda本身中创建一个循环

使用
.split

df['term'] = df['text'].apply(lambda x: x.split()[-1] if x.split()[-1] in myList else None)

仅当字符串始终相同时,使用split方法才有效。必须像这样切换循环和lambda表达式

df = pd.DataFrame(['a red apple',
'a banana yellow ',
'a green melon'], columns=['text'])

the_list = ['apple', 'banana',  'melon']

def fruit_finder(string):
    term_return = 'None'
    for term in the_list:
        if term in string:
            term_return = term
    return term_return

df['term'] = df['text'].apply(fruit_finder)

print(df)
将从列表中返回匹配值

并将产生

               text    term
0       a red apple   apple
1  a banana yellow   banana
2     a green melon   melon

编辑:初始程序不起作用的原因是循环和lambda混淆了。您正在循环使用这些术语,并仅将该术语应用于数据帧(即,您最后一次执行循环时仅检查术语“甜瓜”,因此香蕉和苹果将显示为“无”)

尝试使用
findall

df['new'] = df['text'].str.findall('|'.join(l)).str[0]
Out[66]: 
0     apple
1     apple
2    banana
3     melon
Name: text, dtype: object

“拆分”是否将最后一个单词与文本分开?在真实数据中,目标词可以位于文本中的任何位置。所以这个方法不起作用。我将编辑示例