gpt4 book ai didi

Python 到 CSV : transposing and appending values to list of lists

转载 作者:行者123 更新时间:2023-11-28 22:33:08 25 4
gpt4 key购买 nike

这可能是最基本的,但我时差 react 的大脑拒绝找到解决方案。

我有以下列表(或列表列表):

#"variables" names
name=['a', 'b', 'c']
#variables values
value=[[0,1,1],[0,0,0],[1,1,1]]
#id number of each observation
id=[100,134,26]

我想将输出写入 CSV 文件,使其看起来像这样:

a, b, c, id
0, 1, 1, 100
0, 0, 0, 134
1, 1, 1, 26

我可以毫无问题地将任何单个列表(或列表列表)写入 CSV 文件。但是如何转置 id 列表并将其附加到变量值?将名字堆叠在顶部将是一个很好的奖励。我总是可以创建两个 CSV 文件,但我不想这样做,因为数据操作出错的可能性呈指数级增长。这是我的 CSV 代码编写位(非常标准):

with open('test.csv', 'w', newline='') as f:
wtr = csv.writer(f, delimiter= ',')
wtr.writerows(full_data)
#full_data would be the cleaned data to write into CSV file

谢谢!

最佳答案

没有 Pandas 的一种方法。

import csv

fulldata = [name + ['id']] + [val + [id[i]] for i, val in enumerate(value)]

with open('mycsv.csv','w') as f:
mywriter = csv.writer(f)
mywriter.writerows(fulldata)

会给你:

a,b,c,id                                                                                                        
0,1,1,100
0,0,0,134
1,1,1,26

关于Python 到 CSV : transposing and appending values to list of lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40242186/

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