Matt M
Matt M

Reputation: 309

Apply function to multiple pandas columns with Args

I wrote the following function:

def unique_values(df, column):

unique = df[column].unique()
clean = pd.DataFrame.from_dict(unique)
clean.columns = [column]

return clean

I would like to apply the following function to various columns in a df. As something like this:

unique1, unique2, unique3 = unique_values(df, "Column1", "Column2", "Column3")

If I add an args in the following way:

 def unique_values(df, *column):

    unique = df[column].unique()
    clean = pd.DataFrame.from_dict(unique)
    clean.columns = [column]

    return clean

and apply the function like this:

 unique1, unique2, unique3 = unique_values(df, "Column1", "Column2", "Column3")

I get the following error:

KeyError: ('Column1', 'Column2', 'Column3')

Any help would be appreciated

Upvotes: 0

Views: 389

Answers (2)

Schmuddi
Schmuddi

Reputation: 2086

You can write a small wrapper function that calls your unique_values() function with the list of columns that you pass as arguments, like so:

def df_unique_values(df, *columns):
    return [unique_values(df, x) for x in columns]

This function returns a list containing the result of each call to unique_values() for a different column. Use this function like so:

unique1, unique2, unique3 = df_unique_values(df, "Column1", "Column2", "Column3")

Upvotes: 2

Taku
Taku

Reputation: 33704

You can do it this way by iterating though column:

def unique_values(df, *column):
    to_return=[]
    for col in column:
        unique = df[col].unique()
        clean = pd.DataFrame.from_dict(unique)
        clean.columns = [col]
        to_return.append(clean)
    return to_return
# this way this works:
unique1, unique2, unique3 = unique_values(df, "Column1", "Column2", "Column3")

Upvotes: 2

Related Questions