gpt4 book ai didi

python - 如何计算 csv 文件中的行数并忽略未使用的行(使用 python)

转载 作者:行者123 更新时间:2023-11-30 23:17:37 25 4
gpt4 key购买 nike

我有一个 CSV 文件,其中包含篮球运动员的高度(以英尺和英寸为单位)以及体重。但是,某些数据的脚和高度为 NULL 或空白。

我必须根据体重指数(根据高度和体重计算)得出有多少球员肥胖的结论。

我发现有11名球员是肥胖的。然而,我需要找到数据集中肥胖球员的百分比。我无法弄清楚如何查找玩家总数(忽略那些行中有 NULL 或没有的玩家)。

这是我拥有的数据的示例:

firstname lastname	position firstseason lastseason	h_feet	h_inches weight

Marquis Daniels G 2003 2009 6 6 200
Predrag Danilovic G 1995 1996 6 5 200
Adrian Dantley F 1976 1990 6 5 208
Mike Dantoni G 1975 1975 NULL NULL NULL
Henry Darcey C 1952 1952 6 7 217
Jimmy Darden G 1949 1949 6 1 170
Oliver Darden F 1967 1969 6 6.5 235
Yinka Dare C 1994 1997 7 0 265
Jesse Dark G 1974 1974 6 4.5 210

您可以看到某些行的数据为 NULL。

到目前为止,这就是我的 python 代码:

def read_csv(filename):
"""
Reads a Comma Separated Value file,
returns a list of rows; each row is a dictionary of columns.
"""
with open(filename, encoding="utf_8_sig") as file:
reader = csv.DictReader(file)
rows = list(reader)
return rows

# Try out the function
players = read_csv("players.csv")

# Print information on the first player, to demonstrate how
# to get to the data
from pprint import pprint


def is_obese(player):
if (player["h_inches"] and player["h_feet"] and player["weight"]) == 'NULL' or (player["h_inches"] and player["h_feet"] and player["weight"]) == None:
pass
else:
total_h_inches = float(player["h_feet"]) * 12 + float(player["h_inches"])
bmi = (float(player["weight"])/(total_h_inches**2))* 703
return bmi >= 30


count = 0

for player in players:
if is_obese(player):
print ('player', player["lastname"], 'is obese')
count = count + 1
else:
pass
print ("The total number of obese players:", count)

它返回:

player Boozer is obese
player Brand is obese
player Catlett is obese
player Davis is obese
player Hamilton is obese
player Lang is obese
player Maxiell is obese
player Miller is obese
player Smith is obese
player Traylor is obese
player White is obese
The total number of obese players: 11

最佳答案

同时保留玩家总数的计数器,并且只有在有数据的情况下才将玩家添加到计数器中。

# returns True only if player has all data, otherwise returns False
def has_data(player):
return (player["h_inches"] != 'NULL' and
player["h_feet"] != 'NULL' and
player["weight"] != 'NULL' and
player["h_inches"] is not None and
player["h_feet"] is not None and
player["weight"] is not None)

obese_count = 0
total_count = 0

for player in players:
if has_data(player):
if is_obese(player):
print ('player', player["lastname"], 'is obese')
obese_count += 1
total_count += 1

关于python - 如何计算 csv 文件中的行数并忽略未使用的行(使用 python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27241311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com