首页 > 解决方案 > 使用函数参数过滤 CSV 文件

问题描述

所以我正在编写一个函数来根据函数参数过滤一个csv文件,然后在过滤后找到一列的平均值。我只被允许使用 import csv(没有 pandas)并且不能使用 lambda 或任何其他 python“高级”快捷方式。我觉得我可以轻松获得平均部分,但我无法根据我提到的参数和约束对其进行过滤。我通常会通过使用 pandas 来解决这个问题,这会使这个过程更容易,但我做不到。

这是我的代码:

def calc_avg(self, specific, filter, logic, threshold):
        
        with open(self.load_data, 'r') as avg_file:
            for row in csv.DictReader(avg_file, delimiter= ','):
                specific = row[specific]
                filter = int(row[filter])
                logic = logic
                threshold = 0
                
                if logic == 'lt':
                    filter < threshold
                    
                elif logic == 'gt':
                    filter > threshold
                    
                elif logic == 'lte':
                    filter <= threshold
                    
                elif logic == 'gte':
                    filter >= threshold
                    

它应该与此命令一起使用

print(csv_data.calc_avg("Length_of_stay", filter="SOFA", logic="lt", threshold="15"))

这是代码和列标题的格式。样本数据:

RecordID SAPS-I SOFA    Length_of_stay  
132539    6      1         5    
132540    16     8         8    
132541    21     11       19    
132545    17     2         4    
132547    14     11        6    
132548    14     4         9    
132551    19     8         6    
132554    11     0        17    

标签: pythoncsvfilter

解决方案


您没有对比较结果做任何事情。您需要在if语句中使用它们以在平均计算中包含特定值。

def calc_avg(self, specific, filter, logic, threshold):
    with open(self.load_data, 'r') as avg_file:
        values = []
        for row in csv.DictReader(avg_file, delimiter= ','):
            specific = row[specific]
            filter = int(row[filter])
            threshold = 0

            if logic == 'lt' and filter < threshold:
                values.append(specific)
            elif logic == 'gt' and filter > threshold:
                values.append(specific)
            elif logic == 'lte' and filter <= threshold:
                values.append(specific)
            elif logic == 'gte' and filter >= threshold:
                values.append(specific)
        if len(values) > 0:
            return sum(values) / len(values)
        else:
            return 0

推荐阅读