我有一個 CSV 資料集,其中一個標簽就像這張圖片。

我怎樣才能將這些零和一個保存在單獨的列中?
我的意思是它應該是這樣的圖片:

uj5u.com熱心網友回復:
理論上,您想要的輸出類似于:
label
0,0,0,0,1
0,0,1,0,0
0,0,0,0,1
假設您的 CSV 資料在csvdata這樣的串列中:
csvdata = [[0,0,0,0,1],[0,0,1,0,0]] # ...
你會想做這樣的事情:
with open("csv.csv", "w") as csv:
csv.write("label1,label2,label3,label4,label5")
for row in csvdata: # Get all the rows in our CSV
is_first = True # make sure we don't write a comma on the first cell.
for cell in row: # Now get each of the cells
if not is_first: # Make sure this isn't our first cell
csv.write(",") # Write a comma after the last line if it's not.
csv.write(cell) # Write cell data
is_first = False # Tell the program this isn't our first cell
讓我們分解這段代碼:
在第一行,我們以寫入模式打開 CSV 檔案。然后我們寫我們的標題。行尾為我們處理。
現在我們遍歷每一行,并制作一個標志來告訴程式這是第一個單元格。
現在,在那一行中,我們遍歷我們的單元格
如果它不是該行中的第一個單元格,請寫一個逗號以關閉前一個單元格。
然后,確保程式知道這不是我們在這一行上的第一次運行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/441708.html
上一篇:如何繪制函式的結果?
