[英]Convert wide format csv to long format csv using python
在python中將我的csv數據從寬表格式csv轉換為長格式csv時遇到了一些麻煩。 現在看起來像這樣:
Time Temp1 Temp2 Temp3 Temp4 Temp5
00 21 32 33 21 23
10 34 23 12 08 23
20 12 54 33 54 55
現在,我想將這些數據轉換為長數據格式。 像這樣:
00 temp1 21
00 temp2 32
00 temp3 33
00 temp4 21
00 temp5 23
10 temp1 34
10 temp2 23
10 temp3 12
10 temp4 08
10 temp5 23
20 temp1 12
20 temp2 54
.
.
.
任何有關如何在python中解決此類問題的幫助都將非常有幫助。
您可以使用csv模塊,但邏輯相同。
with open("in.csv") as f,open("out.csv","w") as out:
headers = next(f).split()[1:] # keep headers/Time Temp1 Temp2 Temp3 Temp4 Temp5
for row in f:
row = row.split()
time = row[0]
data = zip(headers, row[1:]) # match correct temp to row item
for a, b in data:
out.write("{} {} {}\n".format(time,a.lower(),b))
print("{} {} {}".format(time,a.lower(),b))
00 temp1 21
00 temp2 32
00 temp3 33
00 temp4 21
00 temp5 23
10 temp1 34
10 temp2 23
10 temp3 12
10 temp4 08
10 temp5 23
20 temp1 12
20 temp2 54
20 temp3 33
20 temp4 54
20 temp5 55
out.csv:
00 temp1 21
00 temp2 32
00 temp3 33
00 temp4 21
00 temp5 23
10 temp1 34
10 temp2 23
10 temp3 12
10 temp4 08
10 temp5 23
20 temp1 12
20 temp2 54
20 temp3 33
20 temp4 54
20 temp5 55
嘗試使用pandas Dataframe存儲csv文件的數據。 它提供了一個內置函數pandas.melt
,它將對您的問題有用。
這是文檔的鏈接 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.