从.txt文件的值求平均值

2024-06-16 11:23:44 发布

您现在位置:Python中文网/ 问答频道 /正文

这就是我的txt文件的样子:

Blancke Karen:16:15:17:15:18
Boddin Sophie:10:10:10:11:9
Bogaert Tim:12:12:13:13:11
Bossuyt Giovanni:14:20:19:19:17
Boucherie Bram:13:12:12:13:12
Brion Mathias:17:18:14:15:9
Brock Christophe:13:12:12:13:8
Brockhoven Karel:12:12:12:13:16
Bruggeman Koen:12:13:12:13:9
Brutyn Andy:3:6:3:6:7
Bulckaen Maarten:11:10:11:11:12
Buster Tim:14:18:17:15:10
Buyse Woudewin:18:15:19:15:20
Caes Roy:8:9:2:0:3
Caljon Thibald:10:10:10:11:12

如何按名称获取所有值的平均值

我已经读了很多关于同一个问题的主题,但是我没有发现像这样的txt文件。 有人能帮我吗


Tags: 文件txtmathiastim样子sophiebramkaren
2条回答

使用pandas很简单:

import pandas as pd

df = pd.read_csv("mytxt.txt", delimiter=':', header=None)

# If you just want to see the results
df.mean(axis=1,numeric_only=True)

# Create a new column to store the results
df['average'] = df.mean(axis=1,numeric_only=True)

df.head(5)
                  0   1   2   3   4   5  average
0     Blancke Karen  16  15  17  15  18     16.2
1     Boddin Sophie  10  10  10  11   9     10.0
2       Bogaert Tim  12  12  13  13  11     12.2
3  Bossuyt Giovanni  14  20  19  19  17     17.8
4    Boucherie Bram  13  12  12  13  12     12.4

本例中使用的txt:https://gofile.io/?c=I6rLX0

I read already many topics about kind of the same question but i found none with a txt file like this one.

因为这是两个不同的任务

读取文件并拆分值

with open('my_file.txt') as f:
    table = [line.rstrip().split(':') for line in f]

现在有了这样的表:

table = [ ['Blancke Karen', '16', '15', '17', '15', '18'],
          ... ]

更改结构并转换数字:

data = {row[0]: list(map(int, row[1:])) for row in table}

你会发现:

data = { 'Blancke Karen': [16, 15, 17, 15, 18],
         ... }

然后用你找到的平均值

相关问题 更多 >