1

refer to this answer (thank you for this answer): Get the name of a pandas DataFrame I'm able to extract variable names in the function, but unfortunately, it doesn't always work (I think that may contain some punctuation like "_") In this case, I want to automatically save correlation plots with dataframe name. Sometimes, it works well while following codes below, however, I don't know why sometimes the saved plot name is just "cor__.png". Could somebody help me figure it out? Thank you so much!!

def get_df_name(df):
    name =[x for x in globals() if globals()[x] is df][0]
    return name

import seaborn as sns
import os

# function of correlation
def cor(data, figsize):
    fig = plt.figure(figsize=figsize)
    corr = data.corr()
    ax = sns.heatmap(
        corr, 
        vmin=-1, vmax=1, center=0,
        cmap=sns.diverging_palette(20, 220, n=200),
        square=True,
        annot = True
    )
    ax.set_xticklabels(
        ax.get_xticklabels(),
        rotation=45,
        horizontalalignment='right'
    )
    
    # path = os.path.join(os.getcwd(), "cor_plots", f"{get_df_namedat}.png")
    path = "cor_plots/cor_{a}.png".format(a = get_df_name(data))
    fig.savefig(fname = path)

for example, I want to save this correlation: cor(df_nodate, figsize=(8,6)), sometimes, it will successfully saved as "cor_df_nodate.png", but it also really often saved as "cor___.png"

miaa
  • 11
  • 3
  • Don't do this. Just *pass in the name you want to use to the function*. Don't try to dynamically recover some global variable name. This is the wrong way to organize your program - keep *program data out of variable names*. – juanpa.arrivillaga Jun 07 '22 at 22:31
  • thank you for your answer!! Would you mind share some example codes that i could just pass in the name and use to the function? – miaa Jun 07 '22 at 22:33
  • I mean like make `name` a paramter`, def cor(data, figsize, name)...` and you call it like `cor(some_df, some_figsize, "whatever_name_I_want")`. Then in your function, you just do `path = "cor_plots/cor_{a}.png".format(name)` – juanpa.arrivillaga Jun 07 '22 at 22:44
  • hahaha got it!! I thought that there would have a more simple way. Thank you! – miaa Jun 07 '22 at 22:50

0 Answers0