如何按照4个元素分组

huangapple go评论137阅读模式
英文:

How to group by 4 elements

问题

以下是您要求的翻译:

  1. 基本上有4个元素按顺序排列,我需要粘贴成4个一组
  2. 我的输入
  3. hr avg(total) avg(rate1) avg(rate2)
  4. 0
  5. 36.27
  6. 0.37
  7. 35.9
  8. 1
  9. 73.26
  10. 11.7
  11. 61.56
  12. 期望输出
  13. hr avg(total) avg(rate1) avg(rate2)
  14. 0 36.27 0.37 35.9
  15. 1 73.26 11.7 61.56
英文:

Basically 4 elements are there in order, i need to paste in group of 4

My input

  1. hr avg(total) avg(rate1) avg(rate2)
  2. 0
  3. 36.27
  4. 0.37
  5. 35.9
  6. 1
  7. 73.26
  8. 11.7
  9. 61.56

Expected out

  1. hr avg(total) avg(rate1) avg(rate2)
  2. 0 36.27 0.37 35.9
  3. 1 73.26 11.7 61.56

答案1

得分: 1

如果您想在不使用pandas的情况下解决问题,您可以使用以下示例(txt是包含来自您的问题的文本的变量):

  1. from io import StringIO
  2. from itertools import groupby
  3. reader = StringIO(txt)
  4. # 读取标题
  5. vals = [next(reader).split()]
  6. # 读取其余部分
  7. for _, g in groupby(enumerate(reader), lambda k: k[0] // len(vals[0])):
  8. vals.append([val.strip() for _, val in g])
  9. for line in vals:
  10. print(*line, sep='\t')

打印输出:

  1. hr avg(total) avg(rate1) avg(rate2)
  2. 0 36.27 0.37 35.9
  3. 1 73.26 11.7 61.56
英文:

If you want solution without pandas, you can use this example (txt is variable containing text from your question):

  1. from io import StringIO
  2. from itertools import groupby
  3. reader = StringIO(txt)
  4. # read headers
  5. vals = [next(reader).split()]
  6. # read the rest
  7. for _, g in groupby(enumerate(reader), lambda k: k[0] // len(vals[0])):
  8. vals.append([val.strip() for _, val in g])
  9. for line in vals:
  10. print(*line, sep='\t')

Prints:

  1. hr avg(total) avg(rate1) avg(rate2)
  2. 0 36.27 0.37 35.9
  3. 1 73.26 11.7 61.56

答案2

得分: 0

  1. print("hr", "avg(total)", "avg(rate1)", "avg(rate2)")
  2. print("{}\t{}\t{}\t{}".format(0, 36.27, 0.37, 35.9))
  3. print("{}\t{}\t{}\t{}".format(1, 73.26, 11.7, 61.56))
  1. output:
  2. hr avg(total) avg(rate1) avg(rate2)
  3. 0 36.27 0.37 35.9
  4. 1 73.26 11.7 61.56
英文:

code:

  1. print("hr","avg(total)","avg(rate1)","avg(rate2)")
  2. print("{}\t{}\t{}\t{}".format(0,36.27,0.37,35.9))
  3. print("{}\t{}\t{}\t{}".format(1,73.26,11.7,61.56))

output:

  1. hr avg(total) avg(rate1) avg(rate2)
  2. 0 36.27 0.37 35.9
  3. 1 73.26 11.7 61.56

huangapple
  • 本文由 发表于 2020年1月6日 19:52:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定