[英]ValueError: arrays must all be same length in python
我嘗試了各種可能性來找出錯誤的原因。 但是沒有發現錯誤的原因。 能否請我幫忙我的代碼出了什么問題。
def businesslogic(dirs, userpath):
data = {}
for fold in dirs:
files = os.listdir(fold)
if 'Test.txt' in files:
with open(os.path.join(fold,'Test.txt'),'r') as te:
lines = [line.rstrip('\n') for line in te.readlines()]
else:
print('Test.txt does not exist')
rows = [value.split(';')[0] for value in lines]
data[fold] = [value.split(';')[1] for value in lines]
df = pd.DataFrame.from_dict(data)---->>>ValueError: arrays must all be same length
df.index = rows
cols = list(df.columns.values)
req = df.loc[['TubeType', 'Digits']]
req = req[cols].astype(int)
由於您的文件夾不一定具有相同數量的文件,因此會出現此錯誤。 使用您的格式,每個文件夾都表示為一列。 並且所有文件夾的第一個文件將在第一行中,第二個文件在第二行中,以此類推...如果在兩個不同的文件夾中有不同數量的文件,則會出現問題。 一個特定的文件夾將需要10行(因為它包含10個文件),而另一個則僅需要8行。Pandas認為這是輸入錯誤。
如果要在同一行中包含所有信息,可以執行以下操作:
# Example a data dict where folders contain different number of files
data= {'folder1' : ['file1', 'file2'], 'folder2' : ['file3'] }
pd.DataFrame({x : [[y for y in data[x]]] for x in data})
輸出:
folder1 folder2
0 [file1, file2] [file3]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.