大家好,我有一个问题。我刚刚学习最小值和最大值。
我无法找到每个类别的五列的最小值和最大值
这是我所拥有的:
我将 5 列 26 列数据从 csv 文件移动到 txt 文件。
例如 .csv 的附加单元格就像
state car motorcycle van airplane bike
Maine 35.5 8.1 5.7 21.0% 33.2%
Michigan 47.9 9.1 5.5 20.40% 25.2%
Washington 52.5 1.2 4.6 3.50% 24.7%
Denver 21.8 20.5 5.3 2.90% 30.9%
我如何让最小值和最大值看起来像这样
min max
car Denver: 21.8 Washington: 52.5
motor Washington: 1.2 Denver: 20.5
van Washington 4.6 Maine: 5.7
airplane Denver 2.90% Maine 21.0%
bike Washington 24.7% Maine 33.2% -
这是我所拥有的
import csv
import string, re
import operator
output = []
data = []
csv_string = []
data_file = []
try:
with open('data.csv', 'r') as csv_string:
for line in csv_string:
cells = line.split(",")
output.append((cells[0], cells[1], cells[5], cells[7], cells[11], cells[13]))
for lines in output:
#state = cells[0]
zmin = cells[1] #car = cells[1]
ymin = cells[1]
xmin = cells[5] #motor = cells[5]
wmin = cells[5]
vmin = cells[7] #van = cells[7]
zmax = cells[7]
ymax = cells[11] #airplane = cells[11]
xmax = cells[11]
wmax = cells[13] #bike = cells[13]
vmax = cells[13]
if cells[1] < xmin:
zmin = cells[1]
if cells[1] > xmax:
zmax = cells[1]
if cells[5] < ymin:
ymin = cells[5]
if cells[5] > ymax:
ymax = cells[5]
if cells[7] < zmin:
xmin = cells[7]
if cells[7] > zmax:
xmax = cells[7]
if cells[11] < zmin:
wmin = cells[11]
if cells[11] > zmax:
wmax = cells[11]
if cells[13] < zmin:
vmin = cells[13]
if cells[13] > zmax:
vmax = cells[13]
outstring = ' '
for item in output:
for cell in item:
outstring += "{0:<35}".format(cell) #Width/Distance of each row
outstring += "\n"
print(outstring)
print('Min: ',zmin,ymin,xmin,wmin,vmin)
print('Max: ',state,zmax,ymax,xmax,wmax,vmax)
finally:
f.close()
try:
f_write = open('output.txt', 'w') #creates the file
try:
f_write.writelines(outstring)
finally:
f.close()
我不确定我做错了什么。我一直在阅读 min 和 max 但我不明白这在附加 5 列时如何应用于 .csv 文件。
如果有人可以提供一些指导,谢谢您的意见。
程序打印错误的数字
print('Min: ',zmin,ymin,xmin,wmin,vmin)
47.9, 8.1, 5.5, 20.40%, 25.2%
print('Max: ',state,zmax,ymax,xmax,wmax,vmax)
21.8, 9.1, 4.6, 20.40%, 30.9%