简体   繁体   中英

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

Could you please give me a hint how to make this work?

I have made a function which should pick specific words from each row depending on the first element of the sentence of each row of a 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]

The dataframe is:

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

And the apply function I try to "apply" to a new column called "description":

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

The required product is a dataframe like this:

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

I tried to express myself as best as I could...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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