python - 使用函数参数过滤 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
解决方案
您没有对比较结果做任何事情。您需要在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
推荐阅读
- javascript - 如何创建与输入文本匹配的搜索栏并仅显示属性中包含该文本的图像(href)???jQuery
- javascript - 用地图在反应组件内打印数字?
- javascript - Javascript 不会在我的 ruby on rails 应用程序中运行,但会在单独的 html/css/js 文件中运行
- c# - Azure Devops 中的集成测试超时 - 停留在将数据写入文件 'C:\Users\VssAdministrator\AppData\Local\ASP.NET\DataProtection-Keys\
- mysql - 如何在MYSQL中将多个select语句的输出带到行数超过1的不同列中
- c# - 无法加载带有平台设置所有 win32 或 x86 的程序集
- wordpress - Woocommerce rest api 不适用于基本身份验证但使用查询字符串
- ios - 在 iOS 上显示用户帖子
- multithreading - 终止程序并关闭所有资源
- javascript - 如何在 Vue.js 中从 JSON 数据创建选择元素?