简体   繁体   English

将 MongoDB 中的数据放入 python 的图表中(使用 pandas 数据框)

[英]Putting data from MongoDB into a chart in python (using pandas dataframe)

I Have a database in MongoDB that shows solar energy production from the year 2019. I imported this in a collection with a json file.我在 MongoDB 中有一个数据库,该数据库显示了 2019 年的太阳能生产情况。我将其导入到带有 json 文件的集合中。 I now have to show this data on a chart in python using the plot() function.我现在必须使用 plot() function 在 python 的图表上显示这些数据。 I read out the data from my MongoDB and put it in a pandas DataFrame.我从我的 MongoDB 中读出数据并将其放入 pandas DataFrame 中。

The issue is that I get a TypeError saying "no numeric data to plot".问题是我收到一个 TypeError 说“没有要绘制的数字数据”。 I assume this is because the data in my dataframe is still in text form and not actual data.我认为这是因为我的 dataframe 中的数据仍然是文本形式,而不是实际数据。 So I somehow need to convert this to numeric data and date times.所以我需要以某种方式将其转换为数字数据和日期时间。

This is my current code:这是我当前的代码:

import pandas as pd
import matplotlib.pyplot as plt
import pymongo

my_client = pymongo.MongoClient("mongodb://localhost:27017/")
my_db = my_client["ExamenVoorbeeld"]
my_collection = my_db["Opbrengst_zonnepanelen"]

lst_power_production = list(my_collection.find(filter={}, projection={"_id": 0, "Production": 1, "DateTime": 1}))

df_mongo = pd.DataFrame(lst_power_production)

print(df_mongo)

df_mongo.plot(x="DateTime", y = "Production", xlabel="date", ylabel="production (kWh)", figsize=(20,10), title="Solar energy production in 2019")

Extra screenshot attached of my database.附加了我的数据库的额外屏幕截图。 Database数据库

You can try changing the datatype of the dataframe columns like:您可以尝试更改 dataframe 列的数据类型,例如:
df_mongo['Production'] = df_mongo['Production'].astype(int)
df_mongo['DateTime'] = pd.to_datetime(df_mongo['DateTime'])

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

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