繁体   English   中英

将 function 应用于 dataframe 每一行的 select 特定单词

[英]Apply function to select specific words from each row of a dataframe

您能否给我一个提示如何使这项工作?

我制作了一个 function ,它应该根据 dataframe 的每一行的句子的第一个元素从每一行中选择特定的单词:

 def distilerator(string):
  '''Input: a dataframe row containing a sentence
     Output: depending on the first word, return a specific selection'''
    if string.str.contains("hello"):
      return string.str.split('\\n')[0]
    else:
      return string.str.split('\\n')[0:2]

dataframe 是:

A             B
hello\blah    456
123\foo\bar   678

而应用 function 我尝试“应用”到一个名为“描述”的新列:

df['description'] = df['A'].apply(distilerator, axis=1) #axis =1 aims to apply to each row

所需的产品是 dataframe,如下所示:

A             B       description
hello\blah    456     hello
123\foo\bar   678     foo bar

我试图尽可能地表达自己...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM