Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将每两行字段转换为包含两行的列_Python_Loops_Rows - Fatal编程技术网

Python 将每两行字段转换为包含两行的列

Python 将每两行字段转换为包含两行的列,python,loops,rows,Python,Loops,Rows,我想将每两行字段转换为包含两行的列。并为每一行循环此转换 这是输入: id refpop001 altpop001 refpop002 altpop002 refpop003 altpop003 id1 6 274 2 93 5 95 id2 202 0 220 0 73 0 id3 166 159 0 173 114 90 这是所需的输出: id pop001 pop002 pop003 id1ref 6 2 5 id1alt

我想将每两行字段转换为包含两行的列。并为每一行循环此转换

这是输入:

id  refpop001   altpop001   refpop002   altpop002   refpop003   altpop003
id1 6   274 2   93  5   95
id2 202 0   220 0   73  0
id3 166 159 0   173 114 90
这是所需的输出:

id  pop001  pop002  pop003
id1ref  6   2   5
id1alt  274 93  95
id2ref  202 220 73
id2alt  0   0   0
id3ref  166 0   114
id3alt  159 173 90

标题和id列仅用于说明,在输出中不需要。

您可以循环输入,然后将其拆分,可能与此类似

int i = 0
for row in input:
  row_array = row.split()
  i = i+=1
  ref = row_array[0] + " " + row_array[2] + " " + row_array[4]]
  alt = row_array[1] + " " +  row_array[3] + " " + row_array[5]

  print "id" + i +"ref " + ref
  print "id" + i + "alt" + alt 

实际上并没有运行此代码,但其想法是这样的,所以在必要时对其进行操作。

鉴于您正在转换文件中以制表符分隔的纯文本,并且您的数据大小没有改变,直接的方法是:

lines=open('file_or_stream_name.txt','r').readlines();

newLines=[]
newLines.append('\t'.join('id','pop001','pop002','pop003')) #header line
for line in lines[1:]:
    elements=line.split('\t')
    newLine=[]
    newLine.append(elements[0]+'ref')
    newLine.extend(elements[1::2])
    newLines.append('\t'.join(newLine))

    newLine=[]
    newLine.append(elements[0]+'alt')
    newLine.extend(elements[2::2])
    newLines.append('\t'.join(newLine))

newText='\n'.join(newLines) #or '\r\n'.join(...), if you're in Windows

请回答您的问题,并向我们展示您的尝试。这是什么?文本文件?熊猫的数据帧?一堆变量?你想要什么样的输出?档案。。。你知道我要说什么吗?我会说这个代码,哈哈。我给出了更多关于如何做的总体想法,而不是解决一些错误的实现。