繁体   English   中英

Pandas 数据框:没有要绘制的数字数据

[英]Pandas dataframe: No numeric data to plot

我有一个表存储在MySQL的数据库中。

我使用 MySQL 连接器获取结果并将其复制到 DataFrame。 到此为止没有任何问题。

现在,当我从 MySQL 获取结果时,它们采用字符串的形式,因此我已将strings转换为int以获取CONFIRMED_CASES的值,并将STATE_NAME保留为str 现在我想将它绘制在条形图中,数字数据为 CONFIRMED_CASES,状态名称为 STATE_NAME,但它显示了这个错误:

Traceback (most recent call last):
  File "c:\Users\intel\Desktop\Covid Tracker\get_sql_data.py", line 66, in <module>
    fd.get_graph()
  File "c:\Users\intel\Desktop\Covid Tracker\get_sql_data.py", line 59, in get_graph
    ax = df.plot(y='STATE_NAME', x='CONFIRMED_CASES',
    ...
    raise TypeError("no numeric data to plot")
TypeError: no numeric data to plot

这是我的代码:

from operator import index
from sqlalchemy import create_engine
import mysql.connector
import pandas as pd
import matplotlib.pyplot as plt

mydb = mysql.connector.connect(
    host="localhost",
    user="abhay",
    password="1234",
    database="covid_db"
)

mycursor = mydb.cursor()


class fetch_data():
    def __init__(self):
        ...

    def get_data(self, cmd):
        ...

    def get_graph(self):
        mydb = mysql.connector.connect(
            host="localhost",
            user="abhay",
            password="1234",
            database="covid_db"
        )

        mycursor = mydb.cursor(buffered=True)

        mycursor.execute(
            "select CONFIRMED_CASES from india;")
        query = mycursor.fetchall()

        # the data was like 10,000 so I removed the ',' and converted it to int
        query = [int(x[0].replace(',', '')) for x in query]
        print(query)

        query2 = mycursor.execute(
            "select STATE_NAME from india;")
        query2 = mycursor.fetchall()

        # this is the query for state name and i kept it as str only...
        query2 = [x[0] for x in query2]
        print(query2)

        df = pd.DataFrame({
            'CONFIRMED_CASES': [query],
            'STATE_NAME': [query2],
        })

        # it gives me the error here...
        ax = df.plot(y='STATE_NAME', x='CONFIRMED_CASES',
                kind='bar')

        ax.ticklabel_format(style='plain', axis='y')
        plt.show()


fd = fetch_data()
fd.get_graph()

我不知道为什么没有数值。 我将它设置为int ,但仍然......

在绘制图形之前使用以下代码将数据转换为整数。

df['CONFIRMED_CASES'] = df['CONFIRMED_CASES'].astype('int64')

您的数据框是使用列表列表定义的。 queryquery2已经是列表。 将您的数据框定义为:

df = pd.DataFrame({
            'CONFIRMED_CASES': query, # no brackets
            'STATE_NAME': query2,     # no brackets
        })

大家好,已经解决了。 我使用了query.values并且它有效......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM