Home > Net >  Calling a specific Pandas Dataframe from user input to use in a function?
Calling a specific Pandas Dataframe from user input to use in a function?

Time:03-30

This might have been answered, but I can't quite find the right group of words to search for to find the answer to the problem I'm having.

Situation: I have a several data frames that could be plugged into a function. The function requires that I name the data frame so that it can take the shape.

def heatmap(table, cmap=cm.inferno, vmin=None, vmax=None, inner_r=0.25, pie_args={}:
     n, m = table.shape

I want the user to be able to specify the data frame to use as the table like this:

table_name= input('specify Table to Graph: ')
heatmap(table_name)

Expectation: If the user input was TableXYZ then the variable table_name would reference TableXYZ so the function would be able to find the shape of TableXYZ to use that information in other parts of the function.

What actually happens: When I try to run the code I get an "AttribureError: 'str' has not attribute 'shape'." I see that the table_name input is a string object, but I'm trying to reference the data frame itself, not the name.

I feel like I'm missing a step to turn the user's input to something the function can actually take the shape of.

CodePudding user response:

I'd recommend assigning each of your dataframes to a dictionary, then retrieving the dataframe by name from the dictionary to pass it to the heatmap function.

For example:

df_by_name = {"df_a": pd.DataFrame(), "df_b": pd.DataFrame()}
table_name= input('specify Table to Graph: ')
df = df_by_name[table_name]
heatmap(df)

Replace pd.DataFrame() in the first line with the actual data frames that you want to select from.

  • Related