计算python中stdin的平均值



我想从stdin中读取python,它看起来像这样:

(Group),(Grade):
1gT,8
1gT,5
1gT,9
1gT,8
1gX,4
1gX,4
1gX,7
1gZ,2
1gZ,9
1gZ,10

现在我想计算每组的平均值。我知道我可以用

从stdin中读取
for line in sys.stdin:

我知道如何计算平均值:

([Sum of all grades from one group] / [number of grades of one group])

但是我如何在Python3中读取每个组的分数并计算它的数量?

感谢大家的思考。多亏了渡边。N帮忙,在你的回答上做了一些修改,它起作用了。

这个为我工作:

import sys
ave = 0
total = 0
count = 0
firstline = sys.stdin.readline()
group, grade = firstline.split()
currentGroup = group
grade = int(grade)
total += grade
count += 1
for line in sys.stdin:
group, grade = line.split()
grade = int(grade)
if currentGroup != group:
print(currentGroup, ave)
count = 1
total = 0 + grade
currentGroup = group
continue
count += 1
total += grade
ave = total/count
else:
print(currentGroup, ave)

import pandas as pd
test = ['1gT',8,
'1gT',5,
'1gT',9,
'1gT',8,
'1gX',4,
'1gX',4,
'1gX',7,
'1gZ',2,
'1gZ',9,
'1gZ',10]
# turn list into dataframe
df = pd.DataFrame(test) 
# rename column
df = df.rename({0: 'Group'}, axis=1)  
# break out columns using even numbers and odd numbers
df = pd.DataFrame({'Group':df['Group'].iloc[::2].values, 'Value':df['Group'].iloc[1::2].values})
# Change value to int
df['Value'] = df['Value'].apply(pd.to_numeric) 
# group and get results
grouped_df = df.groupby("Group")
mean_df = grouped_df.mean()

下面是一个简单的例子。

相关内容

  • 没有找到相关文章

最新更新