使用for循环传递数据框列值的值\迭代循环

时间:2019-10-15 11:01:45

标签: python-3.x pandas numpy

我有一个数据框,其中变量ProblemArea包含值(“屏幕,调制解调器,LTE,音频,视频”)。我使用了for循环来迭代值并根据问题区域进行打印并打印数据框的所有记录。我尝试了以下代码:

import pyodbc
import pandas as pd
import numpy as np
from pandasql import sqldf
crConcat = ''
ProblemArea = ["Screen", "Modem","LTE", "Audio", "video"]
for x in ProblemArea:
    connComp=pyodbc.connect("DSN=sfdc_qct_mirror;autocommit=true")
    #ODS connection string
    server = 'ODSDB'
    db = 'ODS'
    conn = pyodbc.connect()
    SfDf = pd.DataFrame(columns=['casenumber','createddate','RELATED_CRS__C'])
    query_EffQIPL = ("select distinct CASENUMBER, c.CREATEDDATE ,ch.CREATEDDATE as EditDate, c.CLOSEDDATE,PROBLEM_CODE_1__C   where PROBLEM_CODE_1__C = "+ "'"+ x +"'"+  " and OWNER_LOCATION__C = "+ "'Hyderabad'  " )
   EffQIPL_df = pd.read_sql(query_EffQIPL,connComp)
   EffQIPL_df

我仅以PROBLEMArea“视频”盒的形式获得输出,这是循环的最后一个值。

CASENUMBER      PROBLEMArea CR_RELATED_TO_THIS_CASE__C
03860369        Video                  No
03867276        Video                  No
04181458        Video                  Yes
03978455        Video                  Yes
04089497        Video                  No

但是我希望所有PROBLEMAreas的输出都应打印为:

CASENUMBER      PROBLEMArea CR_RELATED_TO_THIS_CASE__C
03860369        Video                  No
03867276        Video                  No
04181458        Video                  Yes
03978455        Video                  Yes
04089497        Video                  No
CASENUMBER      PROBLEMArea CR_RELATED_TO_THIS_CASE__C
09366546        LTE                    NO
98487348        LTE                    YES
CASENUMBER      PROBLEMArea CR_RELATED_TO_THIS_CASE__C
74627267        Screen                 NO
98273476        Screen                 YES
82373498        Screen                 YES

1 个答案:

答案 0 :(得分:0)

这是因为您没有将for循环的变量保存到列表或字典中,所以每次都覆盖它,

尝试一下:(也可以在for循环中清理代码,无需连接字符串)

import pyodbc
import pandas as pd
import numpy as np
from pandasql import sqldf
crConcat = ''
ProblemArea = ["Screen", "Modem","LTE", "Audio", "video"]


connComp=pyodbc.connect("DSN=sfdc_qct_mirror;autocommit=true")
ODS connection string
server = 'ODSDB'
db = 'ODS'
conn = pyodbc.connect()
# is this needed?    
# SfDf = pd.DataFrame(columns=['casenumber','createddate','RELATED_CRS__C'])


dfs = []

for x in ProblemArea:

   query_EffQIPL = ("select distinct CASENUMBER, c.CREATEDDATE ,ch.CREATEDDATE as EditDate, c.CLOSEDDATE,PROBLEM_CODE_1__C   where PROBLEM_CODE_1__C = "+ "'"+ x +"'"+  " and OWNER_LOCATION__C = "+ "'Hyderabad'  " )

   dfs.append(pd.read_sql(query_EffQIPL,connComp))

final_ = pd.concat(dfs)