简体   繁体   中英

Python - return dataframe and list from function

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?

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)

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)

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