pmainstone
pmainstone

Reputation: 11

Getting user input to select a Pandas object

I wish to get a user to select a pandas object. Each object contains just two columns and may have a number of rows. The objects (for the sake of this question) are object1 and object2.

import pandas as pd
object1 = pd.read_csv(file1.csv)
object2 = pd.read_cdv(file2.csv)
def printTable(tableName):
    # tableName.shape[0]           # Gets the number of rows in the table
    # len(tableName.columns)       # Gets number of columns in the table
    for row in range(0, tableName.shape[0]):    # SHAPE is number of rows in Table
        line = ""
        for column in range(0, len(tableName.columns)):
            line += str(tableName[list(tableName)[column]][row]) + " : "
        print (line)

printTable (object1)   # This works fine and prints my object

# but the following code throws an error
# "AttributeError: 'str' object has no attribute 'shape'
# How do get the User to select the object?
while True:            
    tableName = input("\nEnter a table name: \n")
    if tableName:
        printTable(tableName)
    else:
        break

Upvotes: 1

Views: 1526

Answers (2)

progmatico
progmatico

Reputation: 4964

You may store your objects in a dict using strings as keys. Then the user inputs the key string and you use it to retrieve the corresponding object.

Something like:

table_map = {'table1':object1, 'table2': object2}

table_name = input('Input table name:')
printTable(table_map[table_name])

Upvotes: 1

boot-scootin
boot-scootin

Reputation: 12515

Why not store things in a dictionary, like so?

import pandas as pd
object1 = pd.read_csv(file1.csv)
object2 = pd.read_cdv(file2.csv)

# This is the dictionary, a key-value mapping
# We can lookup the key 'object1' (or whatever table name, in your case)
# and return the "table"/DataFrame associated to which that key maps
table_lookup = {'object1': object1, 'object2': object2}

def printTable(tableName):
    table = table_lookup[tableName]
    rows, columns = table.shape
    for row in range(rows):
        # do something like print the row

# but the following code throws an error
# "AttributeError: 'str' object has no attribute 'shape'
# How do get the User to select the object?
while True:            
    tableName = input("\nEnter a table name: \n")
    if tableName:
        printTable(tableName)
    else:
        break

input will return a str object, not the actual namespace referring to a variable. So tableName will be 'object1', not object1. Do you see the difference?

Upvotes: 2

Related Questions