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。我强调嵌套循环有问题,但是我无法解决问题。
答案 0 :(得分:0)
我认为使用如下所示的词典从用户输入创建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)