如何在csv表中进行行到列的数据转置? [英] How to do row-to-column transposition of data in csv table?

查看:297
本文介绍了如何在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表中进行行到列的数据转置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆