简体   繁体   English

小数点后第二位停止平均值

[英]Stopping averages after the 2nd decimal point

I got this code to work but I wanted to get the part I print out to stop at the after 2 numbers after the decimal point (0.00) I don't know how to go about doing this could anyone give some insight of what command I would use to do this. 我可以使用此代码,但我想打印的部分停在小数点(0.00)后的2个数字处,我不知道该怎么做,任何人都可以对我的命令有所了解将用于执行此操作。 This is the code 这是代码

import csv

#turn csv files into a list of lists
with open('train.csv','rU') as csvfile:
     reader = csv.reader(csvfile)
     csv_data = list(reader)
with open ('train.csv', 'r') as f:
    numline = len(f.readlines())

# Create two lists to handle the patients
# And two more lists to collect the 'sum' of the columns
# The one that needs to hold the sum 'must' have 0 so we 
# can work with them more easily
iList = []
iList_sum = [0,0,0,0,0,0,0,0,0,0,0,0,0]
IPcounter = 0
hList = []
hList_sum = [0,0,0,0,0,0,0,0,0,0,0,0,0]
HPcounter = 0

# Only use one loop to make the process mega faster
for row in csv_data:
    # If row 13 is greater than 0, then place them as unhealthy
    if (row and int(row[13]) > 0):
        # This appends the whole 'line'/'row' for storing :)
        # That's what you want (instead of saving only one cell at a time)
        iList.append(row)
        IPcounter += 1

    # If it failed the initial condition (greater than 0), then row 13
    # is either less than or equal to 0. That's simply the logical outcome
    else:
        hList.append(row)
        HPcounter += 1


# Loop through all the 'rows' of the ill patient 
for ill_data in iList:

    # Loop through the data within each row, and sum them up
    qmark_counter = 0
    for i in range(0,len(ill_data) - 1):
        if ill_data[i] == '?':
            val = 0

        else:
            val = ill_data[i]
        iList_sum[i] += float(val)



# Now repeat the process for healthy patient
# Loop through all the 'rows' of the healthy patient 
for healthy_data in hList:

    # Loop through the data within each row, and sum them up
    for i in range(0,len(healthy_data) - 1):
        hList_sum[i] += float(ill_data[i])


ill_avg = [ ill / len(iList) for ill in iList_sum]
hlt_avg = [ hlt / len(hList) for hlt in hList_sum]



print('Total number of lines ' + str(numline))
print("Total amount of healthy patients " + str(HPcounter))
print("Total amount of ill patients " + str(IPcounter))
print("Averages of healthy patients " + str(hlt_avg))
print("Averages of ill patients " + str(ill_avg))

This is the output 这是输出

    Total number of lines 303
Total amount of healthy patients 164
Total amount of ill patients 139
Averages of healthy patients [57.0, 0.0, 2.0, 130.0, 236.0, 0.0, 2.0, 174.0, 0.0, 0.0, 2.0, 1.0, 3.0]
Averages of ill patients [56.62589928057554, 0.8201438848920863, 3.5899280575539567, 134.568345323741, 251.4748201438849, 0.15827338129496402, 1.1726618705035972, 139.25899280575538, 0.5467625899280576, 1.5741007194244607, 1.8273381294964028, 1.129496402877698, 5.798561151079137]

You can use round(number, ndigits) where ndigits is the number of decimal places. 您可以使用round(number, ndigits) ,其中ndigits是小数位数。

For example 例如

>>> number = 32.32434354
>>> round(number, 2)
32.32
>>> round(number, 5)
32.32434

An alternative is using Python's str.format() . 一种替代方法是使用Python的str.format()

For example 例如

>>> '{:.2f}'.format(number)
'32.32'
>>> '{:.5f}'.format(number)
'32.32434'

Where, 哪里,

  • {} is .format() 's position to insert the number. {}.format()插入数字的位置。

  • The f specifies the number will be a float . f指定数字为float

  • The .2 or .5 means to round it to two or five decimal places. .2.5表示将其舍入到两位或五个小数位。

An alternative is to use the string .format method. 一种替代方法是使用字符串.format方法。 Documentation for the specifiers is here . 说明符的文档在这里 The {} designate where a replacement will occur in the string, f says the replacement will be a float, and .2 tells it to only show 2 digits after the decimal. {}指定字符串中将出现替换的位置, f表示替换将是浮点数, .2告诉它仅在小数点后显示2位数字。

print('{:.2f}'.format(32.32434))
# Prints 32.32

To print an array of numbers, with each formatted: 要打印数字数组,每种格式都需要:

num_list = [1.2345, 2.3456, 3.4567, 4.5678]
print('[' + ', '.join(['{:.2f}'.format(number) for number in num_list]) + ']')
# Prints [1.23, 2.35, 3.46, 4.57]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM