熊猫iterrows()跳过指定的行

时间:2019-12-16 18:31:56

标签: python pandas dataframe

我正在代码中运行一个循环,该循环从保存在计算机上的Excel工作表中提取SQL查询,然后执行该查询。每次查询运行完毕后,它将转到下一行,并执行此操作,直到没有更多查询为止。但是,我想在其中添加用户可以跳过某些行的位置(出于运行时的目的)。这是我的循环现在的样子:

import 'package:flutter/material.dart';

main() => runApp(MaterialApp(home: MyApp()));

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _string = 'You haven\'t pressed a button yet' ;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Notification demo'),),
      body: NotificationListener<IntegerNotification>(
        onNotification: (IntegerNotification notification){
          print(notification.value);
          setState(() {
            _string = 'You have pressed button ${notification.value} times.';
          });
          return true;
        },
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(_string),
            ChildWidget(),
          ],
        ),
      ),
    );
  }
}

class ChildWidget extends StatefulWidget {
  @override
  _ChildWidgetState createState() => _ChildWidgetState();
}

class _ChildWidgetState extends State<ChildWidget> {
  int _counter = 0;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: RaisedButton(
        child: Text('Increment'),
        onPressed: () {
          IntegerNotification(++_counter).dispatch(context);
        },
      ),
    );
  }
}

class IntegerNotification extends Notification {
  final value;

  IntegerNotification(this.value);
}

因此,selected_rows是用户从UI中选择的行,从而跳过查询3。什么是完成我想做的最有效方法?感谢您的指导或提示!

3 个答案:

答案 0 :(得分:0)

您可以将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

答案 1 :(得分:0)

我想您可以添加该条件以在循环内作为if语句跳过。

答案 2 :(得分:0)

由于我不了解所有详细信息,因此我将尽力编辑您的代码以最简单的方式解决问题。

selected_rows = ['1', '2', '4', '5']

for index in range(len(loop_file)):
    if str(index) in selected_rows:
        row = loop_file.iloc[index]
        print('run_toleau(): ' + 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..#toleau') is not null drop table #toleau'

cursor.execute(clean_up)

return outer_df

需要注意的是,如果完全关注性能,则最好避免iterrows()。

相关问题