我有一个daraframe,它为每个OfficeLocation
返回数据
如何按每个OfficeLocation
拆分dataframe,并将每个数据段插入单独的excel电子表格。你知道吗
import pandas
import pyodbc
server = 'MyServer'
db = 'MyDB'
myparams = ['2019-01-01','2019-02-28', None] # None substitutes NULL in sql
connection_string = pyodbc.connect('DRIVER={SQL Server};server='+server+';DATABASE='+ db+';Trusted_Connection=yes;')
df = pandas.read_sql_query('EXEC PythonTest_Align_RSrptAccountCurrentMunich @EffectiveDateFrom=?,@EffectiveDateTo=?,@ProducerLocationID=?', connection_string, params = myparams)
# sort the daraframe
df.sort_values(by=['OfficeLocation'], axis=0,inplace=True)
# set the index to be this and do not drop
df.set_index(keys=['OfficeLocation'],drop=False,inplace=True)
# get a list of unique offices
office = df['OfficeLocation'].unique().tolist()
# now we can perform a lookup on a 'view' of the dataframe
SanDiego = df.loc['San Diego']
print(SanDiego)
# how can I iterate through each office and create excel file for each office
df.loc['San Diego'].to_excel((r'\\user\name\Python\SanDIego_Office.xlsx'))
所以我需要3个excel电子表格和数据:SanDiego.xlsx,
Vista.xlsx
和SanBernardino.xlsx
像这样简单的事情怎么样?你知道吗
编辑
我已经生成了50000行与你类似的数据。你知道吗
并创建了两个函数,一个使用我的版本,另一个使用groupby方法。你知道吗
如果有人怀疑它们的性能相似,但groupby方法的方差较小,运行时间也快了1秒。你知道吗
您可以使用
groupby
:相关问题 更多 >
编程相关推荐