1

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

2 Answers 2

2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

I have implemented this and it works a treat. The 'object1' is the key in the table referring to object1. Using a dictionary in this way is extremely useful. I'm very new to Python, but enjoying the steep learning curve!
1

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.