【问题标题】:Create Columns based on keywords and check if it present or not根据关键字创建列并检查它是否存在
【发布时间】:2019-12-02 16:09:11
【问题描述】:

我是编程新手。我遇到了一个问题。我想为关键字创建列并检查关键字是否存在于文本列中,如果存在则在该特定关键字列中返回关键字,否则返回空值。你能帮我解决这个问题吗? image for list of my keywords

现在我想创建作为列表项的列并检查文本中存在的项目,如果它们存在则返回该项目,否则返回空值?

【问题讨论】:

  • 举个例子分享一下
  • 如果你先向我们展示你做了什么,你的输入是什么样的,你的输出应该是什么样的,那就太好了。您可以阅读this guide 以检查如何使用最小可行示例提出问题:)
  • 查看图片,请回答我的问题
  • 我想将每个项目创建为新列,如果列表存在则返回该项目,否则返回空值。

标签: python-3.x pandas


【解决方案1】:

据我了解,您的意思可能是这样的:

import pandas as pd

# Define dataframe
df = pd.DataFrame(data={'text': ['the quick brown fox', 'jumps over', 'the lazy dog']})

# DataFrame looks like
#                   text
# 0  the quick brown fox
# 1           jumps over
# 2         the lazy dog

# Define keywords
keyword_list = ['the', 'fox', 'dog']

# Function to find keyword in text
def find_keyword(text, keyword):
    if keyword in text:
        return keyword

# Loop over keywords and apply function, then save result in column called like the keyword
for keyword in keyword_list:
    df[keyword] = df['text'].apply(lambda t: find_keyword(t, keyword))


# DataFrame looks like
#                  text   the   fox   dog
# 0  the quick brown fox   the   fox  None
# 1           jumps over  None  None  None
# 2         the lazy dog   the  None   dog

【讨论】:

  • 我这样做了,但我收到类型错误,即 float 类型的参数不可迭代
  • @pavansamanthgoli 抱歉,如果您不共享代码,真的很难帮助您。请编辑您的问题并尝试写下您所做的以及如果您遇到错误复制/粘贴确切的错误。您不应该使用指向图像的链接,而应该在您的问题本身中编写代码。 This is a guide to formattingthis is a guide to make your question acceptable。请仔细阅读
  • 嗨@UJIN 可以联系我吗
猜你喜欢
  • 2021-01-09
  • 1970-01-01
  • 2018-05-21
  • 2021-04-19
  • 1970-01-01
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多