1

I want to create a function in Python that returns both a list and a data frame. I know how to do this with two seperate functions, but is there a way to return both from a single function?

import pandas as pd
# sample data
data_dict = {'unit':['a','b','c','d'],'salary':[100,200,250,300]}
# create data frame
df = pd.DataFrame(data_dict)
# Function that returns a dataframe
def test_func(df):
    # create list meeting some criteria
    mylist = list(df.loc[(df['salary']<=200),'unit'])
    # create new dataframe based on mylist
    new_df = df[df['unit'].isin(mylist)]
    return new_df
# create dataframe from function
new_df = test_func(df)

The above function returns just the data frame. How do I also return mylist in the same function?

2

2 Answers 2

4

You can simply return two variables in the function

import pandas as pd
# sample data
data_dict = {'unit':['a','b','c','d'],'salary':[100,200,250,300]}
# create data frame
df = pd.DataFrame(data_dict)
# Function that returns a dataframe
def test_func(df):
    # create list meeting some criteria
    mylist = list(df.loc[(df['salary']<=200),'unit'])
    # create new dataframe based on mylist
    new_df = df[df['unit'].isin(mylist)]
    return new_df, my list

# create dataframe and list from function
new_df, mylist = test_func(df)
Sign up to request clarification or add additional context in comments.

Comments

0

just place comma and add anything you want, but remember in function calling must give same return variables.

return new_df, my list

new_df, mylist = test_func(df)

Comments

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.