嗨,我是第一次使用python,可能在这里犯了一个愚蠢的错误。 需要从数据框中的sql查询结果更新字典的值。对此有任何帮助。
import xlwings as xw
import pyodbc
import pandas as pd
print("Libraries imported")
print()
print()
print("Creating list of measures to load.")
ListOfVariables = ['RegDrv_Sex','Quote_NCD']
print()
print()
print("Creating default dictionaries to load.")
RegDrv_Age = {'16':0,'17 To 20':0,'21 To 24':0,'25 To 29':0,'30 To
34':0,'35 To 39':0,'40 To 44':0,'45 To 49':0,'50 To 54':0,'55 To 59':0,'60
To 64':0,'65 To 69':0,'70 To 74':0,'75 To 79':0,'Over 79':0}
Quote_NCD = {'0':0,'1':0,'2':0,'3':0,'4':0,'5':0,'6':0,'7':0,'8':0,'9':0}
ListofDictionaries = [RegDrv_Sex,Quote_NCD]
Server = "odsprd"
DataBase = "Staging"
#connection propertry
connection = pyodbc.connect('Driver={SQL Server};'
'Server=' + Server + ';'
'Database=' + DataBase + ';'
'Trusted_Connection=yes;')
print()
print()
print("Connected To " + DataBase)
cursor = connection.cursor()
wb = xw.Book(r'C:\PythonApplication1\Overall.xlsx')
sht = wb.sheets['Sheet1']
print()
print()
print("Excel Template Imported.....")
#Source Data
df = sqlquery = pd.read_sql_query("SELECT Variable,Value,AquoteVolume FROM [staging].dbo.aggmitest WITH (NOLOCK) ORDER BY Variable,Value", connection)
print()
print()
print("Source Data Frame Loaded....")
row=0
for variable in ListOfVariables:
print()
print()
print(variable + " dictionary loaded....")
# update dictonary with values
df_foreach_variable = df.loc[df.Variable == variable]
#print(df_foreach_variable)
df_select = df_foreach_variable.loc[:,['AquoteVolume']]
#print(df_select)
for Dictionary in ListofDictionaries :
for item in Dictionary:
if item in df_select:
Dictionary.update({item:df_select[item]})
print()
print()
print(Dictionary)
# Print to Excel
row = 0
print()
print()
print("Printing Excel....")
for Dictionary in ListofDictionaries :
row+=3
for i in Dictionary:
Cell='B'+str(row)
wb.sheets['Sheet1'].range(Cell).value = Dictionary[i]
row+=1
print()
print()
print("Excel Print Complete!")
wb.save(r'C:PythonApplication1\Overall2.xlsx')
预期结果:字典值应由DF中的值更新 实际结果:字典仅显示默认值。
将SQLquery的结果插入RegDrv_Age的数据框:
Value AquoteVolume
16 69
17 To 20 96662
21 To 24 137143
25 To 29 156386
30 To 34 126831
35 To 39 103091
40 To 44 81725
45 To 49 77763
50 To 54 69705
55 To 59 52046
60 To 64 35648
65 To 69 25095
70 To 74 19887
75 To 79 11156
Over 79 6793