【问题标题】:Python | how do i make a program that calculates math蟒蛇 |我如何制作一个计算数学的程序
【发布时间】:2019-03-04 11:36:21
【问题描述】:

我正在尝试使用 Python 3 创建代码来导入文本文件 到 python,将其转换为列表,然后用它计算一些东西,比如平均分。

文本文件:

number name subject1 subject2 subject3 subject4 subject5
1234567 Jun 5 7 0 6 4
3526435 Merie 5 5 7 0 0
2230431 Kaes 6 10 0 8 6
7685433 Endré 4 7 8 7 5
0364678 Ontoinette 0 2 8 8 8
1424354 Yerôme 7 9 0 5 0
4536576 Mamal 8 0 8 7 8
1256033 Eiana 0 0 0 0 0
5504657 Wetra 6 6 7 0 6
9676575 Aalika 0 6 0 0 8
0253756 Oamira 3 8 6 7 10

【问题讨论】:

    标签: python arrays python-3.x list text-files


    【解决方案1】:

    如果您乐于使用第三方库,您可以使用 Pandas。使用这种方法不需要“转换为列表”,因为数据在 NumPy 数组中的保存效率更高。

    import pandas as pd
    
    # read input file
    df = pd.read_csv('file.csv')
    
    # calculate mean, ignoring 0 values
    df['mean'] = df.iloc[:, 2:].astype(float).replace(0, np.nan).mean(1)
    
    # iterate rows and print results
    for name, mean in df.set_index('name')['mean'].items():
        print(f'{name} has average of {mean:.2f}')
    

    输出:

    Jun has average of 5.50
    Merie has average of 5.67
    Kaes has average of 7.50
    Endré has average of 6.20
    Ontoinette has average of 6.50
    Yerôme has average of 7.00
    Mamal has average of 7.75
    Eiana has average of nan
    Wetra has average of 6.25
    Aalika has average of 7.00
    Oamira has average of 6.80
    

    【讨论】:

    • 我是否必须将 file.csv 更改为 file.txt 但是当我尝试这样做时会出错。
    • @Doughnut,见Load data from txt with pandas
    • 当我尝试这样做时,它给了我一个错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 4: unexpected end of data
    • @Doughnut,这在 SO 上已经出现了很多次。你搜索了吗?
    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多