gpt4 book ai didi

python - 使用 Python 在 CSV 文件中添加列

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:29 25 4
gpt4 key购买 nike

我有如下所示的 csv 文件(输入文件):

Temperature,2,3
Temperature,5,6
Pressure,11,14,45
Pressure,13,23,16
Humidity,21,24,25
Humidity,27,28,26

我想将它写入另一个文件(输出文件),但格式如下:

Temperature,2,3,Pressure,11,14,45,Humidity,21,24,25
Temperature,5,6,Pressure,13,23,16,Humidity,27,28,26

我试过以下 Python 代码:

with open('inputFile.csv','r') as csvinput:
with open('outputFile.csv','w') as csvoutput:
writer = csv.writer(csvoutput, delimiter= ',')
writer = csv.writer(csvoutput)
for row in csv.reader(csvinput):
if (row[0] == "Pressure" or row[0] == "Humidity"):
type =row[0]
Value = row[1])
writer.writerow(row + [np.asarray(type)] + [np.asarray(Value)])

输出格式如下:

Temperature,2,3,Humidity,27

Temperature,5,6,Humidity,27

Temperature,8,9,Humidity,27

Pressure,11,14,45,Pressure,11

Pressure,13,23,16,Pressure,13

Humidity,21,24,25,Humidity,21

Humidity,27,28,26,Humidity,27

请帮忙!

最佳答案

缺少二进制模式。

为了提高可读性,我建议将读取、更改数据和写入分开,因为您必须在写入之前读取整个输入文件。

示例(没有错误处理):

  import csv
f = open('inputFile.csv','rb')
reader = csv.reader(f)
data = {}
keys = set ()
for row in reader :
key = row [0]
data.setdefault (key, []).append (row)
f.close ()
odata = []
for (t, p, h) in zip (data ["Temperature"], data ["Pressure"], data ["Humidity"]) :
odata.append (t + p + h)
g = open('outputFile.csv','wb')
writer = csv.writer (g)
writer.writerows (odata)
g.close ()

关于python - 使用 Python 在 CSV 文件中添加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42885458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com