gpt4 book ai didi

python - 查找列中的关键字并将这些关键字添加到同一行的新列中

转载 作者:太空宇宙 更新时间:2023-11-03 19:45:46 25 4
gpt4 key购买 nike

我是 python 新手,这是我关于堆栈溢出的第一篇文章。我有一个关键字列表和一个包含多列的数据框。

我想在特定列中搜索这些关键字并编写出现在该列中的关键字。

这就是我正在做的事情。 My code

这是我收到的错误。 The loop with the error

这就是我想要得到的。 Desired output

请帮助找出问题所在或提出更好的方法。谢谢!如果可以使事情变得更容易,请编写下面的代码。

import pandas as pd

keywords = ["hello","hi","greetings","wassup"]

data = ["hello, my name is Harry", "Hi I am John", "Yo! Wassup", "Greetings fellow traveller","Hey im
Henry", "Hello there General Kenobi"]

df = pd.DataFrame(data,columns = ['strings'])

df['Keywords'] = ""

df2 = pd.DataFrame(data = None, columns = df.columns)

for word in keywords:
temp = df[df['strings'].str.contains(word,na = False)]
temp.reset_index(drop = True)
temp['Keywords'] = word
df2.append(temp)

错误:

C:\Users\harka\Anaconda3\lib\site-packages\ipykernel_launcher.py:5:SettingWithCopyWarning:尝试在 DataFrame 的切片副本上设置一个值。尝试使用 .loc[row_indexer,col_indexer] = value 代替

请参阅文档中的警告:http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy “”“

最佳答案

我添加了“Yo”以表明它可以返回多个字符串

import pandas as pd

def keyword(row):
strings = row['strings']
keywords = ["hello","hi","greetings","wassup",'yo']
keyword = [key for key in keywords if key.upper() in strings.upper()]
return keyword

data = ["hello, my name is Harry", "Hi I am John", "Yo! Wassup", "Greetings fellow traveller","Hey im Henry", "Hello there General Kenobi"]

df = pd.DataFrame(data,columns = ['strings'])
df['keyword'] = df.apply(keyword, axis=1)

如果您不喜欢返回的字符串列表,那么也许是逗号分隔的字符串?

import pandas as pd

def keyword(row):
strings = row['strings']
keywords = ["hello","hi","greetings","wassup",'yo']
keyword = [key for key in keywords if key.upper() in strings.upper()]
return ','.join(keyword)

data = ["hello, my name is Harry", "Hi I am John", "Yo! Wassup", "Greetings fellow traveller","Hey im Henry", "Hello there General Kenobi"]

df = pd.DataFrame(data,columns = ['strings'])
df['keyword'] = df.apply(keyword, axis=1)

关于python - 查找列中的关键字并将这些关键字添加到同一行的新列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60147791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com