【问题标题】:Convert wide format csv to long format csv using python使用python将宽格式csv转换为长格式csv
【发布时间】:2015-01-13 20:45:05
【问题描述】:

在 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 中解决此类问题的帮助都会非常有帮助。

【问题讨论】:

  • 时间列表示经过的时间(以秒为单位),而 Temp 1 、Temp2、Temp 3、Temp 4、Temp 5 列表示该时刻不同传感器的温度。

标签: python csv


【解决方案1】:

你可以使用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

【讨论】:

  • 如果文件真的被可变长度的空格分隔,这可能比csv更自然。
【解决方案2】:

尝试使用 pandas Dataframe 来存储 csv 文件的数据。它提供了一个内置函数pandas.melt,这对您的问题很有用。

这是文档的link

【讨论】:

    猜你喜欢
    • 2018-01-31
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 2021-07-20
    • 1970-01-01
    相关资源
    最近更新 更多