How to dynamically create pandas dataframes

Viewed 37

I'm creating a script where I would like to end out with 5 dataframes - the script is being handover to the marketing department, so I would like to avoid additional coding.

tables = [onegram, twogram, threegram, fourgram, original]
def calc_rate(table):
    table['Interaction rate'] = table['Interactions'] / table['Impr.']
    table['Interaction rate'] = table['Interaction rate'].replace(np.nan, 0)
    table['Interaction rate'] = table['Interaction rate'].replace(np.inf, 0)
    table['Conv. rate'] = table['Conversions'] / table['Interactions']
    table['Conv. rate'] = table['Conv. rate'].replace(np.nan, 0)
    table['Conv. rate'] = table['Conv. rate'].replace(np.inf, 0)
    table['Cost / conv'] = table['Cost'] / table['Conversions']
    table['Cost / conv'] = table['Cost / conv'].replace(np.nan, 0)
    table['Cost / conv'] = table['Cost / conv'].replace(np.inf, 0)
    table['Avg. cost'] = table['Cost'] / table['Interactions']
    table['Avg. cost'] = table['Avg. cost'].replace(np.nan, 0)
    table['Avg. cost'] = table['Avg. cost'].replace(np.inf, 0)
    
    i = 1
    for table in tables: 
        calc_rate(table)
        print("table {} is done".format(i))
        i+=1 

This is the last part of the code (working) Now I want to create a dataframe for each of them taking top 100 sorted by Interactions - something like this inside the same function:

       for table in tables: 
           table.add_suffix('_interaction_sorted') = table.sort_values(by="Interactions", ascending=False).head(100) 

I would like to end up with:

onegram_interactions_sorted
twogram_interactions_sorted
threegram_interactions_sorted
fourgram_interactions_sorted
original_interactions_sorted

it obviously does not work, but how could i make it work??

1 Answers

Try this

table1 = table.sort_values(by="Interactions", ascending=False).head(100)
table1 = table1.add_suffix('_interaction_sorted')

or if you want same name

table = table.sort_values(by="Interactions", ascending=False).head(100)
table = table.add_suffix('_interaction_sorted')
Related