gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:03:25 25 4
gpt4 key购买 nike

我希望让用户选择一个 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

最佳答案

为什么不像这样将东西存储在字典中?

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。你看出区别了吗?

关于python - 获取用户输入以选择 Pandas 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53558269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com