#!/bin/python3
import csv
import statistics
def read_cvs():
with open('hw_25000.csv', 'r') as csv_rf:
cvs_reader = csv.DictReader(csv_rf)
for line in cvs_reader:
print(line[' "Height(Inches)"'])
read_cvs()
我有這段代碼可以讀取我的檔案并列印出我的高度值,但我不確定如何使用 statistics.mode() 列印出最常見的高度值。
CSV 檔案位于 https://people.sc.fsu.edu/~jburkardt/data/csv/csv.html
uj5u.com熱心網友回復:
#嘗試這個
print(statistics.mode(line[' "Height(Inches)"']))
uj5u.com熱心網友回復:
該檔案中的標題在每個列名的文本之前包含一個額外的空格。這可以通過使用skipinitialspace=True選項來洗掉。此外,CSV 閱讀器會將所有內容作為字串讀取,因此這些值需要轉換為浮點數。
嘗試以下方法:
import csv
import statistics
def read_cvs():
heights = []
with open('hw_25000.csv', 'r') as csv_rf:
cvs_reader = csv.DictReader(csv_rf, skipinitialspace=True)
for line in cvs_reader:
heights.append(float(line['Height(Inches)']))
print(statistics.mode(heights))
read_cvs()
對于您的示例 CSV 檔案,這給出了:
70.04724
一個較短的版本是:
def read_cvs():
with open('hw_25000.csv', 'r') as csv_rf:
cvs_reader = csv.DictReader(csv_rf, skipinitialspace=True)
print(statistics.mode(float(line['Height(Inches)']) for line in cvs_reader))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/455914.html
標籤:Python python-3.x CSV
