python - pandas iterrows() 跳过指定的行
问题描述
我在我的代码中运行一个循环,从保存在我计算机上的 Excel 表中提取 SQL 查询,然后执行该查询。每次查询完成运行时,它都会转到下一行并执行此操作,直到没有更多查询为止。但是,我想添加用户可以根据需要跳过某一行的位置(出于运行时目的)。这是我的循环现在的样子:
selected_rows = ['1', '2', '4', '5']
for index, row in loop_file.iterrows():
print('run(): ' + row['Name'])
query = row['Logic']
inner_df = pd.read_sql_query(query, conn)
if inner_df.empty:
continue
inner_df['project_id'] = pr_id
inner_df['logic_name'] = row['Name']
outer_df = pd.concat([outer_df, inner_df], axis=0, ignore_index=True, sort=False)
clean_up = 'if object_id ('tempdb..#table') is not null drop table #table'
cursor.execute(clean_up)
return outer_df
所以 selected_rows 将是用户从 UI 中选择的行,跳过查询 3。完成我想要做的事情的最有效方法是什么?感谢您的任何指示或提示!
解决方案
您可以将selected_rows
用作数据框的索引。
像这样:
# this is assumed to be the index
selected_rows = [1, 2, 4, 5]
# filter to only contain the selected indices
filtered = loop_file[selected_rows]
# proceed as previously
for index, row in filtered.iterrows():
print('run(): ' + row['Name'])
query = row['Logic']
inner_df = pd.read_sql_query(query, conn)
if inner_df.empty:
continue
inner_df['project_id'] = pr_id
inner_df['logic_name'] = row['Name']
outer_df = pd.concat([outer_df, inner_df], axis=0, ignore_index=True, sort=False)
clean_up = 'if object_id ('tempdb..#table') is not null drop table #table'
cursor.execute(clean_up)
return outer_df
推荐阅读
- java - 我的 HttpURLConnection 请求有什么问题?
- asynchronous - 为等待中的对象字段分配新值会阻止进一步的说明
- html - 带有当前 URL 的 Facebook 评论计数器
- javascript - Webpack 无法解析库中使用的 @(别名)导入
- javascript - 将密码重置令牌插入未受保护的 NodeJS 路由
- css - Safari 不尊重 @Keyframes 不透明度/填充
- python - 如何使用 Flask-SQLAlchemy 从数据库中仅选择某些列?
- c++ - 修改 n 维矩阵的 TypedArray 位置
- spring-boot - 尽管存在`@Transactional`,为什么这些数据库修改不回滚?
- csv - 是否可以生成只读 CSV 文件?