我想以特定格式將資料保存在 csv 檔案中,但出現錯誤。附加了所需的輸出。
import numpy as np
import csv
N=2
Pe = np.array([[[128.22918457, 168.52413295, 209.72343319],
[129.01598287, 179.03716051, 150.68633749],
[131.00688309, 187.42601593, 193.68172751]],
[[ 64.11459228, 84.26206648, 104.86171659],
[ 64.50799144, 89.51858026, 75.34316875],
[ 65.50344155, 93.71300796, 96.84086375]]])
with open('Test123.csv', 'w') as f:
for x in range(0,N):
print([Pe[x]])
writer = csv.writer(f)
# write the data
writer.writerows(zip(x,Pe[x]))
錯誤是
TypeError: 'int' object is not iterable
所需的輸出是

uj5u.com熱心網友回復:
with open('Test123.csv', 'w') as f:
for x in range(0 ,N):
print([Pe[x]])
writer = csv.writer(f)
# write the data
header = [x] * len(Pe[x])
# header = [x] ['']*(len(Pe[x])-1)
writer.writerows(zip(header, Pe[x]))
在zip函式中,引數需要__iter__函式來執行。
所以TypeError: 'int' object is not iterable發生錯誤,因為int物件沒有這個功能。
將x變數設為串列型別,然后它就可以作業了。
uj5u.com熱心網友回復:
代替
writer.writerows(zip(x,Pe[x]))
和
writer.writerows(zip([x],[Pe[x]]))
發生這種情況是因為索引將回傳物件而不是此處的可迭代容器
uj5u.com熱心網友回復:
問題在于 zip 函式,它需要一個可迭代的(我們可以回圈的東西)。您可以簡單地在檔案中寫入一行。我還沒有找到一個很好的方法,但這就是我想出的。
我還建議使用 len() 函式而不是手動設定 n ,以及使用 snake_case (也適用于您的變數!)。
import numpy as np
pe = np.array([[[128.22918457, 168.52413295, 209.72343319],
[129.01598287, 179.03716051, 150.68633749],
[131.00688309, 187.42601593, 193.68172751]],
[[ 64.11459228, 84.26206648, 104.86171659],
[ 64.50799144, 89.51858026, 75.34316875],
[ 65.50344155, 93.71300796, 96.84086375]]])
# Loop over the subarrays in pe
with open('Test123.csv', 'w') as f:
for i in range(len(pe)):
# Create the line by appending the index and the array, separated by a comma.
line = str(i) ',' str(pe[i])
# Add the number and the subarray
f.write(line)
ps:如果您在錯誤中包含行號,下次會更容易幫助您!
更新:您使用其他答案中的 writerows 的方法可能更好,但我希望這個答案對您仍然有用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/493032.html
上一篇:文本檔案行到csv列
