如何在迭代和附加到列表时解决 ValueError

How to solve ValueError while iterating and appending to list

ValueError:传递了 2 列,传递的数据有 4 列:

import pandas as pd    
def customedata():
    colnum = input("How many columns do you need? ")
    colnum = int(colnum)
    rownum = input("How many rows do you need? ")
    # user input column and row
    rownum = int(rownum)
    colName = []
    rowName = []
     # create an empty list

    for col in range(0,colnum):
           colValue =input('Enter the value for column name of column %s:' %(col + 1))
           colName.append(colValue)
           for row in range(0,rownum):
                  rowValue = (int(input('Enter the value of row number %s:' %(row + 1))))
                  rowName.append(rowValue)
                  row = row + 1
                  col = col + 1
    # columns = colName[i]
    df1= pd.DataFrame([rowName],columns = colName)
    print(df1)

我尝试使用用户输入的行和列创建数据框,但我一直收到 valueError。我认为嵌套循环有问题,但我无法解决问题。

我认为使用如下字典根据用户输入创建 pd.DataFrame 会更容易。首先创建一个空 dict,然后将 colName 作为键传递,将 rowName 列表作为值传递。然后你可以使用 pd.DataFrame.from_dict() 将你的字典转换为 pd.DataFrame

希望对您有所帮助:)

def customedata():
    colnum = input("How many columns do you need? ")
    colnum = int(colnum)
    rownum = input("How many rows do you need? ")
    # user input column and row
    rownum = int(rownum)
    colName = []
    rowName = []
    dictionary = {}
    for col in range(0, colnum):
        colValue = input('Enter the value for column name of column %s:' % (col + 1))
        for row in range(0, rownum):
            rowValue = (int(input('Enter the value of row number %s:' % (row + 1))))
            rowName.append(rowValue)
        dictionary[colValue] = rowName
    df1 = pd.DataFrame.from_dict(dictionary)
    print(df1)