我让这段代码工作,但我想让我打印出来的部分停在小数点后的 2 个数字 (0.00) 我不知道该怎么做,任何人都可以提供一些见解我将使用什么命令来执行此操作。 这是代码
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))
这是输出
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]
最佳答案
您可以使用 round(number, ndigits)
其中 ndigits
是小数位数。
例如
>>> number = 32.32434354
>>> round(number, 2)
32.32
>>> round(number, 5)
32.32434
另一种方法是使用 Python 的 str.format()
.
例如
>>> '{:.2f}'.format(number)
'32.32'
>>> '{:.5f}'.format(number)
'32.32434'
在哪里,
{}
是.format()
插入数字的位置。f
指定数字将是一个float
。.2
或.5
表示四舍五入到小数点后两位或五位。
关于python - 小数点后第二位的停止平均数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36588093/