快速将大型Salesforce查询读入熊猫

时间:2019-02-22 08:22:20

标签: python-3.x pandas simple-salesforce

使用simple_salesforce连接器,我的查询返回了c.150k条记录,而将数据读取到数据框中的以下方法花费了很长时间,以至于我刚进入SF,运行报告,下载并读取到熊猫。有没有更快的方法?谢谢

import pandas as pd
from simple_salesforce import Salesforce

fields = ['field' + str(i) for i in range(1, 10)]
fields_str = ", ".join(fields)
query_str = "select {} from account".format(fields_str)

sf = Salesforce(username= myusername, password= mypwd, security_token = mytoken)
df = sf.query_all(query_str)

sf_df = pd.DataFrame(columns = fields)

for account in range(df['totalSize']):
     account_dict = {}
     for field in fields:
         account_dict[field] = df['records'][account][field]
     dict_df = pd.DataFrame.from_dict([account_dict])
     sf_df = sf_df.append(dict_df, sort=False)
     del(account_dict)

1 个答案:

答案 0 :(得分:0)

您可以使用['records']键直接提取记录。

df = sf.query_all('SELECT ID, CreatedDate FROM Account LIMIT 10')['records']
df = pd.DataFrame(df)
df

或作为单个代码行:

df = pd.DataFrame(sf.query_all('SELECT ID, Createddate FROM Account LIMIT 10')['records'])
df

如果attributes列不包含要查看的数据,则可以使用.drop(columns=['attributes']将其从返回的数据框中删除。

df = sf.query_all('SELECT ID, CreatedDate FROM Account LIMIT 10')['records']
df = pd.DataFrame(df)
df.drop(columns=['attributes'],inplace=True)
df

或作为单个代码行:

df = pd.DataFrame(sf.query_all('SELECT ID, Createddate FROM Account LIMIT 10')['records']).drop(columns=['attributes'])
df