1

I have a function that take two argument and return two arguments I want to pass and return two arguments

I tried this but doesn't work I get error TypeError: expected string or bytes-like object

df['col1'], df['col2'] = zip(*df.apply(lambda x: myfunc(df['description'], df['title']), axis=1))
2
  • What's the type of input and output arguments. Are they a String? Commented Nov 30, 2021 at 8:13
  • the output are word_tokenize & sent_tokenize and the inputs are String Commented Nov 30, 2021 at 9:15

1 Answer 1

1

Trying to write a small example:

import pandas as pd

df = pd.DataFrame({"Description":["A", "B"], "Title":["Hello1", "Hello2"]})

def myfunc(x,y): return x+y, y+x

df['col2'] = df.apply(lambda x: myfunc(x['Description'], x['Title']), axis=1)

df

OUTPUT

 Description   Title                col2
0           A  Hello1  (AHello1, Hello1A)
1           B  Hello2  (BHello2, Hello2B)

When you use .apply(func, axis=1), the function is applied line by line, and each line is the x. In other words, when you process the first line, x["Description"] is "A" and x["Title"] is "Hello2". As you can see, the lambda function written in your code does not use the x at any point, but it refers to the global df.

FOLLOW UP: to answer your question if we can have 2 columns:

df[["col1"]], df[["col2"]] = zip(*(df.apply(lambda x: myfunc(x['Description'], x['Title']), axis=1)))

OUTPUT

 Description   Title     col1     col2
0           A  Hello1  AHello1  Hello1A
1           B  Hello2  BHello2  Hello2B
Sign up to request clarification or add additional context in comments.

1 Comment

is it not possible to have two columns ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.