将所有值组合写入csv

时间:2016-01-26 15:34:45

标签: python csv

我想创建一个包含以下格式的csv文件。对于第一列,ABC重复3次,AAA1也重复3次。然后AAA1递增1成为AAA2然后再递增1成为AAA3。我想重复这样的增量N次,然后切换到BBB1并重复N次。以下是我的代码。我知道他们错了。请帮帮我。

with open(file.csv, 'r') as input:
    reader = csv.reader(input,lineterminator='\n', delimiter = ',')

    all = []
    row = next(reader)
    all.append(row)
    alist= ["AAA","BBB"]
    count=0
    for row in reader:
        count+=1
        row.insert(2, (random.choice(alist)+ (str(count)))) 
        all.append(row)

with open(file.csv, 'w') as output:
    writer = csv.writer(output, lineterminator='\n',delimiter = ',')   

这就是我想要创造的东西

enter image description here

Block ID    Stage ID
A      AAA1                 
B      AAA1                         
C      AAA1                         
A      AAA2                         
B      AAA2                         
C      AAA2                         
A      BBB1                         
B      BBB1                         
C      BBB1                         
A      BBB2                         
B      BBB2                         
C      BBB2                         

2 个答案:

答案 0 :(得分:1)

我相信这就是你要做的事情:

  number_of_times_to_repeat_stage_prefix = 4
  stage_prefixes = ["AAA","BBB"]
  block_ids = list('ABC')
  text = []
  for stage_prefix in stage_prefixes:
      block_counter = 0
      for i in range(number_of_times_to_repeat_stage_prefix):
          for block in block_ids:
              text.append([block, stage_prefix + str(block_counter+1)])
          block_counter+=1

  with open("E:/file.csv", 'w') as output:
      writer = csv.writer(output, lineterminator='\n',delimiter = ',')
      writer.writerows(text)

重复设置为4后,我得到:

A   AAA1
B   AAA1
C   AAA1
A   AAA2
B   AAA2
C   AAA2
A   AAA3
B   AAA3
C   AAA3
A   AAA4
B   AAA4
C   AAA4
A   BBB1
B   BBB1
C   BBB1
A   BBB2
B   BBB2
C   BBB2
A   BBB3
B   BBB3
C   BBB3
A   BBB4
B   BBB4
C   BBB4

答案 1 :(得分:0)

你最初有一个R标签,不确定你是否对R解决方案开放,但是这里有:

NN <- 2 #"repeat N times..."
DF <- data.frame("Block ID" = LETTERS[1:3],
                 "Stage ID" = paste0(rep(c("AAA", "BBB"), each = 3 * NN),
                                     rep(1:NN, each = 3)))
write.csv(DF, file = "file.csv")