如何在csv表中进行数据的行到列转置?

编程入门 行业动态 更新时间:2024-10-05 09:29:02
本文介绍了如何在csv表中进行数据的行到列转置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是脚本新手.我有一个表 (Table1.txt),我需要创建另一个表,其中 Table1 的行按列排列,反之亦然.我已经找到了针对 Perl 和 SQL 而不是 Python 的解决方案.

I'm new to scripting. I have a table (Table1.txt) and I need to create another table that has Table1's rows arranged in columns and vice versa. I have found solutions to this problem for Perl and SQL but not for Python.

我两天前才开始学习 Python,所以就我所掌握的:

I just started learning Python two days ago, so this is as far as I got:

import csv import sys with open(sys.argv[1], "rt") as inputfile: readinput = csv.reader(inputfile, delimiter=' ') with open("output.csv", 'wt') as outputfile: writer = csv.writer(outputfile, delimiter=" ") for row in readinput: values = [row[0], row[1], row[2], row[3]] writer.writerow([values])

这只是将列复制为列.我现在想做的是将最后一行写为 writer.writecol([values]) 但似乎没有这样的命令,我还没有找到另一种写法行作为列.

This just reproduces the columns as columns. What I would have liked to do now is to write the last line as writer.writecol([values]) but it seems that there is no command like that and I haven't found another way of writing rows as columns.

推荐答案

转置迭代序列的一般解决方案是:zip(*original_list)

The solution in general to transpose a sequence of iterables is: zip(*original_list)

样本输入:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

计划:

with open('in.txt') as f: lis = [x.split() for x in f] for x in zip(*lis): for y in x: print(y+' ', end='') print(' ')

输出:

1 6 11 2 7 12 3 8 13 4 9 14 5 10 15

更多推荐

如何在csv表中进行数据的行到列转置?

本文发布于:2023-07-09 10:12:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1085558.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   如何在   csv   行到列转置

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!