Aaron Lin
Aaron Lin

Reputation: 41

Python- Unpack A List in Pandas Slicer

I wrote a function that does something similar like following. The function expects a multi-level dataframe. column_name argument can be ['Deal Name','Deal Expense']. To filter a multi-level dataframe, I would need to unpack the column_name list inside a dataframe filter.

I was hoping something like df[*column_name].loc[row_name] would work, but it didn't.

More Info: I'm trying to access a multilevel data frame. column_name[0] is the name of the column I want on level 0, column_name[1] is the name of the column I want on level 1, so on and so forth.

def search_table(row_name, column_name):
    if header == 1:
        output = df.at[row_name, column_name]
    elif header == 2:
        output = df[column_name[0], column_name[1]].loc[row_name]
    elif header == 3:
        output = df[column_name[0], column_name[1], column_name[2]].loc[row_name]
    elif header == 4:
        output = df[column_name[0], column_name[1], column_name[2], column_name[3]].loc[row_name]
    return output

This function does the job, but it's really silly to write. How can I unpack a list inside a dataframe slicer?

Upvotes: 1

Views: 186

Answers (1)

Alexander Wiens
Alexander Wiens

Reputation: 26

I'm not exactly sure I understood what your header parameter does, pandas dataframes can be sliced by an array of column names. Therefore you may directly access by an array of columns without the python list unpacking operator (*) like this:

def search_table(row_name, column_name):
    if header == 1:
        return df.at[row_name, column_name]
    elif header >= 2:
        return df[column_name].loc[row_name]

Upvotes: 1

Related Questions