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

编程入门 行业动态 更新时间:2024-10-04 15:26:45
本文介绍了如何在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='\t') with open("output.csv", 'wt') as outputfile: writer = csv.writer(outputfile, delimiter="\t") 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+'\t', end='') print('\n')

输出:

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

更多推荐

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

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

发布评论

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

>www.elefans.com

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