如何按照4个元素分组

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

How to group by 4 elements

问题

以下是您要求的翻译:

基本上有4个元素按顺序排列,我需要粘贴成4个一组

我的输入

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

期望输出

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

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

My input

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

Expected out

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

答案1

得分: 1

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

from io import StringIO
from itertools import groupby

reader = StringIO(txt)

# 读取标题
vals = [next(reader).split()]
# 读取其余部分
for _, g in groupby(enumerate(reader), lambda k: k[0] // len(vals[0])):
    vals.append([val.strip() for _, val in g])

for line in vals:
    print(*line, sep='\t')

打印输出:

hr	avg(total)	avg(rate1)	avg(rate2)
0	36.27	0.37	35.9
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):

from io import StringIO
from itertools import groupby

reader = StringIO(txt)

# read headers
vals = [next(reader).split()]
# read the rest
for _, g in groupby(enumerate(reader), lambda k: k[0] // len(vals[0])):
    vals.append([val.strip() for _, val in g])

for line in vals:
    print(*line, sep='\t')

Prints:

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

答案2

得分: 0

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

code:

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

output:

hr avg(total) avg(rate1) avg(rate2)
0	36.27	0.37	35.9
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:

确定