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

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

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