英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论