How do I reference a dataframe using a variable that holds the dataframe name?

Viewed 299

I have the following dataframes: pack, armor, sword, bow. Each has ~100 rows and each has an id column as the index and another column called name. This is a simplified version of one dataframe:

pack=pd.DataFrame(columns=['id','name','capacity']).set_index('id')
packs.loc[1]=['Small Backpack',15]
...

My inventory contains the word pack and then the id number of the pack I have; the word armor and the id number of the armor I have, and so on.

inventory = [
        ('pack','1'),
        ('armor','3'),
        ('sword','2'),
        ('bow','1')
        ]

I'm creating a function that should produce a result that looks like:

pack: Small Backpack
armor: Steel Armor
sword: Wooden Sword
bow: Hardened Bow

In the XXXXX spot below I need to call the name of the item but don't know how.

def command_inventory():
    for a,b in inventory:
        print(a+':',XXXXX)
1 Answers

You can achieve that by create a dictionary which will map the inventory keywords to dataframes, then we can select the column name and select the value based on index.

inventory = [
    ('pack','1'),
    ('armor','3'),
    ('sword','2'),
    ('bow','1'),
]

df_map = {
    'pack': pack,
    'armor': armor,
    'sword': sword,
    'bow': bow,
}

for a, b in inventory:
    print(f"{a}: {df_map[a]['name'][int(b)]}")
Related