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

2024-06-29 01:07:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我必须根据他们的身高和体重计算出他们的体重指数来推断有多少球员肥胖。在

我发现有11名球员肥胖。然而,我需要在数据集中找到肥胖玩家的百分比。我很难弄清楚如何找到玩家的总数(忽略那些在他们的行中有空或没有的玩家)。在

以下是我的数据示例:

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代码如下:

然后返回:

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


Tags: 文件csv数据高度is玩家nullplayer
2条回答

添加count_total

count_total = 0
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:
    count_total +=1  # to count number of playes without NULL values
    total_h_inches = float(player["h_feet"]) * 12 + float(player["h_inches"])
    bmi = (float(player["weight"])/(total_h_inches**2))* 703
    return bmi >= 30

最后:

^{pr2}$

也要为玩家总数保留一个计数器,并且只有在计数器上有数据时才添加玩家。在

# 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

相关问题 更多 >