Search code examples
pythonpandassalesforcesoql

Python Pandas / Sales force SOQL: how to pass list to SOQL query using for loop?


I want to do a code that irritates on a list and use it in SOQL query to get output and appended to excel sheet.

That's my code, is there any cleaner way to do this.

 ExlReport=pd.read_excel(ExlReportPath,sheet_name=ExlSheetName)
 CaseNumberList = [] IdList = [] IdList = ExlReport['Id']

 for Id in IdList:
             results = sf.query_all ("SELECT LastModifiedDate,Case,Id FROM Case_Note  WHERE Case = '%s' ORDER BY LastModifiedDate ASC" %
 soqlEscape(Id)) sf_df =
 pd.DataFrame(results['records']).drop(columns='attributes')

Expected Output:

  LastModifiedDate             Case           Id 
0  2020-02-19T23:31:35.000+0000  xxxxxxxxxxxx  yyyyyyyyyyyy  
1  2020-02-19T23:31:43.000+0000  xxxxxxxxxxxx  yyyyyyyyyyyy 
2  2020-03-11T20:48:54.000+0000  xxxxxxxxxxxx  yyyyyyyyyyyy  

Output I get:

0  2020-02-19T23:31:35.000+0000  xxxxxxxxxxxx  yyyyyyyyyyyy  
1  2020-02-19T23:31:43.000+0000  xxxxxxxxxxxx  yyyyyyyyyyyy 
2  2020-03-11T20:48:54.000+0000  xxxxxxxxxxxx  yyyyyyyyyyyy  

 new_axis = axis.drop(labels, errors=errors)
  File "C:\xxxxxxx", line 5018, in drop
    raise KeyError(f"{labels[mask]} not found in axis")
KeyError: "['attributes'] not found in axis"

Solution

  • I resolved the issue by using dropna in order to be able to pass the dataframe neat and tidy to the excel sheet.

    sf_df=(sf_df).dropna(axis=0,how='any')
    Appended_df=pd.DataFrame((sf_df).drop(columns='attributes'))
    

    Check this link for dropna.

    Complete Code:

        import pandas as pd
        ExlReport=pd.read_excel(ExlReportPath,sheet_name=ExlSheetName)
        CaseNumberList = []
        IdList = [] 
        IdList = ExlReport['Id']
        Appended_df = pd.DataFrame()
        sf_df=pd.DataFrame()
    
    
        for Id in IdList:
               results = sf.query_all ("SELECT LastModifiedDate,Case,Id FROM Case_Note  WHERE Case='%s' ORDER BY LastModifiedDate ASC" % soqlEscape(Id)) 
               sf_df =pd.DataFrame(results['records']).drop(columns='attributes')
               df = pd.DataFrame(results['records'])
               sf_df = sf_df.append(df)
    
        sf_df=(sf_df).dropna(axis=0,how='any')
        Appended_df=pd.DataFrame((sf_df).drop(columns='attributes'))