【问题标题】:Make a bar graph visualization using python with data from SQL Database使用 python 和来自 SQL 数据库的数据制作条形图可视化
【发布时间】:2023-02-21 13:13:52
【问题描述】:

我尝试使用 SQL 数据库中的数据用 python 制作条形图可视化。我不知道我哪里出错了,并得到了这样的错误。感谢您的关注。

# Import data visualization packages
import matplotlib.pyplot as plt
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=DESKTOP-G28VNS8\SQLEXPRESS;'
                      'Database = IRACADEMY;'
                      'Trusted_Connection = yes;')
cursor = conn.cursor()

# Selecting first column to select name and second column
# to select marks
cursor.execute('Select science, MyStudentId from 
               IRACADEMY.dbo.Marks1')
result = cursor.fetchall()
studentIds = [i[1] for i in result]
print(studentIds)
# 'Converting Data Set into a List '
sciencemarks = [i[0] for i in result]
print(sciencemarks)
#conn.commit()
# x-coordinates of left sides of bars
x = 'studentId' 
# y-coordinates height of of bars
y = 'sciencemarks'
# labels for bars - Name of student
tick_label = [i[1] for i in result]
# plotting a bar chart
plt.bar(x, y, tick_label=tick_label,
width=0.5, color=['orange','red', 'green'])
# plot title
plt.title('Students Science Marks Details')
# naming the x-axis
plt.xlabel('Ids of Students')
# naming the y-axis
plt.ylabel('Science Marks')
# function to show the plot
plt.show()


ValueError Traceback(最近的 最后调用) C:\Users\THINKP~1\AppData\Local\Temp/ipykernel_21592/636037255.py 在

ValueError:操作数无法与一起广播 重新映射的形状 [original->remapped]: (3,) 和请求的形状 (1,)

【问题讨论】:

  • 如果您打印出所获得的查询结果,将会很有帮助。你能发布结果的输出吗

标签: python sqlconnection


【解决方案1】:

你有你的输出。即使我也面临这个问题。

import numpy
import pandas as pd
import matplotlib.pyplot as plt
import pyodbc as pyodbc
import seaborn as sns
from tabulate import tabulate
conx_string = "driver={SQL Server}; server=IE3BLT7ZFGXD3SQLEXPRESS; database=DB01; trusted_connection=YES;"
with pyodbc.connect(conx_string) as conx:
    cursor = conx.cursor()
    conx.setdecoding(pyodbc.SQL_CHAR, encoding='latin1')
    conx.setencoding('latin1')
    cursor.execute("SELECT firstname from Custlog")
    data = cursor.fetchall()
    

with pyodbc.connect(conx_string) as conx:
    cursor = conx.cursor()
    conx.setdecoding(pyodbc.SQL_CHAR, encoding='latin1')
    conx.setencoding('latin1')
    cursor.execute("SELECT gender from Custlog")
    data1 = cursor.fetchall()
    
    

with pyodbc.connect(conx_string) as conx:
    cursor = conx.cursor()
    conx.setdecoding(pyodbc.SQL_CHAR, encoding='latin1')
    conx.setencoding('latin1')
    cursor.execute("SELECT age from Custlog")
    data2 = cursor.fetchall()
    

with pyodbc.connect(conx_string) as conx:
    cursor = conx.cursor()
    conx.setdecoding(pyodbc.SQL_CHAR, encoding='latin1')
    conx.setencoding('latin1')
    cursor.execute("SELECT dept from Custlog")
    data3 = cursor.fetchall()
    

with pyodbc.connect(conx_string) as conx:
    cursor = conx.cursor()
    conx.setdecoding(pyodbc.SQL_CHAR, encoding='latin1')
    conx.setencoding('latin1')
    cursor.execute("SELECT id from Custlog")
    data4 = cursor.fetchall()
    
  

with pyodbc.connect(conx_string) as conx:
    cursor = conx.cursor()
    conx.setdecoding(pyodbc.SQL_CHAR, encoding='latin1')
    conx.setencoding('latin1')
    cursor.execute("SELECT team_no from Custlog")
    data5 = cursor.fetchall()
    
   

table = {'Firstname':data, 'Gender':data1, 'Age':data2,'Department':data3,'Id':data4,'Team_no':data5}
df = pd.DataFrame(table)
print(df)
sns.lineplot( df['Age'], df['Team_no'])

this is the output of the data i have in my db that i've extracted in python.

    C:Users......Anaconda3libsite-packagesseaborn_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
  warnings.warn(
Traceback (most recent call last):
  File "C:Users......Anaconda3libsite-packagesseaborn_core.py", line 1479, in categorical_order
    order = vector.cat.categories
  File "C:Users......Anaconda3libsite-packagespandascoregeneric.py", line 5575, in __getattr__
    return object.__getattribute__(self, name)
  File "C:Users......Anaconda3libsite-packagespandascoreccessor.py", line 182, in __get__
    accessor_obj = self._accessor(obj)
  File "C:Users......Anaconda3libsite-packagespandascorerrayscategorical.py", line 2717, in __init__
    self._validate(data)
  File "C:Users......Anaconda3libsite-packagespandascorerrayscategorical.py", line 2726, in _validate
    raise AttributeError("Can only use .cat accessor with a 'category' dtype")
AttributeError: Can only use .cat accessor with a 'category' dtype

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:Users......source
eposdemo1demo1demo1.py", line 62, in <module>
    sns.lineplot( df['Age'], df['Team_no'])
  File "C:Users......Anaconda3libsite-packagesseaborn_decorators.py", line 46, in inner_f
    return f(**kwargs)
  File "C:Users......Anaconda3libsite-packagesseaborn
elational.py", line 708, in lineplot
    p._attach(ax)
  File "C:Users......Anaconda3libsite-packagesseaborn_core.py", line 1137, in _attach
    seed_data = categorical_order(seed_data)
  File "C:Users......Anaconda3libsite-packagesseaborn_core.py", line 1483, in categorical_order
    order = vector.unique()
  File "C:Users......Anaconda3libsite-packagespandascoreseries.py", line 2088, in unique
    return super().unique()
  File "C:Users......Anaconda3libsite-packagespandascorease.py", line 989, in unique
    result = unique1d(values)
  File "C:Users......Anaconda3libsite-packagespandascorelgorithms.py", line 440, in unique
    uniques = table.unique(values)
  File "pandas_libshashtable_class_helper.pxi", line 5361, in pandas._libs.hashtable.PyObjectHashTable.unique
  File "pandas_libshashtable_class_helper.pxi", line 5310, in pandas._libs.hashtable.PyObjectHashTable._unique
TypeError: unhashable type: 'pyodbc.Row'
Press any key to continue . . .

          this is the error i am facing. i want to do clustering with the data i've extracted from the db using python.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 1970-01-01
    相关资源
    最近更新 更多