Получение пользовательского ввода для выбора объекта Pandas - PullRequest
0 голосов
/ 30 ноября 2018

Я хочу, чтобы пользователь выбрал объект панды.Каждый объект содержит только два столбца и может иметь несколько строк.Объектами (ради этого вопроса) являются 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 голосов
/ 30 ноября 2018

Вы можете хранить свои объекты в диктовке, используя строки в качестве ключей.Затем пользователь вводит строку ключа, и вы используете ее для извлечения соответствующего объекта.

Что-то вроде:

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

table_name = input('Input table name:')
printTable(table_map[table_name])
0 голосов
/ 30 ноября 2018

Почему бы не сохранить вещи в словаре, например, так?

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.Вы видите разницу?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...