【问题标题】:How to solve ValueError while iterating and appending to list如何在迭代和附加到列表时解决 ValueError
【发布时间】:2020-10-08 10:17:43
【问题描述】:

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。我坚持认为嵌套循环有问题,但我无法解决问题。

【问题讨论】:

  • 我认为你应该删除 row = row + 1col = col + 1

标签: python pandas dataframe nested-loops valueerror


【解决方案1】:

我认为使用如下字典从用户输入创建pd.DataFrame 会更容易。首先创建一个空的dict,然后将colName 作为键传递,rowNamelist 作为值传递。然后您可以使用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)

【讨论】:

  • 很高兴我能帮上忙 :)
猜你喜欢
  • 1970-01-01
  • 2023-03-23
  • 2020-07-26
  • 2021-06-24
  • 1970-01-01
  • 2014-09-06
  • 1970-01-01
  • 1970-01-01
  • 2013-02-17
相关资源
最近更新 更多