获取用户输入以选择Pandas对象

时间:2018-11-30 13:11:58

标签: python pandas

我希望让用户选择一个熊猫对象。每个对象仅包含两列,并且可以具有许多行。 (出于这个问题的考虑)对象是object1和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 个答案:

答案 0 :(得分:2)

为什么不像这样将内容存储在字典中?

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将返回str对象,而不是引用变量的实际名称空间。因此tableName将是'object1',而不是object1。你看到区别了吗?

答案 1 :(得分:1)

您可以使用字符串作为键将对象存储在字典中。然后,用户输入密钥字符串,然后使用它来检索相应的对象。

类似的东西:

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

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