[英]Converting nested dictionary to pandas dataframe and plotting
I have a listener which is constantly logging received messages in the following way --我有一个监听器,它通过以下方式不断记录收到的消息——
class Listener:
recorded = defaultdict(lambda: defaultdict(list))
def on_message_received(self, msg):
self.recorded[msg.id]["timestamp"].append(msg.timestamp)
self.recorded[msg.id]["data"].append(msg.data)
It can be assumed both the timestamp and data are floats.可以假设时间戳和数据都是浮点数。
For a single id, I can plot the data with --对于单个 id,我可以使用 plot 数据 -
import altair as alt
import pandas as pd
import streamlit as st
listener = Listener()
plt, frame = st.empty(), st.empty()
def plot():
c = listener.recorded.copy()
df = pd.DataFrame.from_dict(c[100]) # using id: 100 as an example
chart = alt.Chart(df).mark_line().encode(x="timestamp", y="data")
frame.write(df)
plt.altair_chart(chart)
Which produces a dataframe and plot of:它产生一个 dataframe 和 plot :
So my question is, how would I back up a level and generate a dataframe/plot from the dictionary listener.recorded
so that each unique id is plotting correctly with a legend?所以我的问题是,我将如何备份一个级别并从字典
listener.recorded
生成一个数据框/绘图,以便每个唯一的 id 都正确地绘制一个图例? I cannot seem to quite get there on my own...我自己似乎无法完全到达那里......
You can create the dataframe with pd.concat
, reset the index, and then use Altair as normal.您可以使用 pd.concat 创建
pd.concat
,重置索引,然后正常使用 Altair。 Here's a short example with data similar to the dictionary you are generating:这是一个简短的示例,其数据类似于您正在生成的字典:
import altair as alt
import pandas as pd
import numpy as np
rng = np.random.default_rng(1701)
data = {
100: {'timestamp': pd.date_range('2021-01-01', periods=10, freq='D'),
'data': np.random.randint(0, 100, 10)},
200: {'timestamp': pd.date_range('2021-01-01', periods=10, freq='D'),
'data': np.random.randint(0, 100, 10)},
300: {'timestamp': pd.date_range('2021-01-01', periods=10, freq='D'),
'data': np.random.randint(0, 100, 10)},
}
df = pd.concat({k: pd.DataFrame(d) for k, d in data.items()})
df = df.reset_index(0).rename({'level_0': 'id'}, axis=1)
alt.Chart(df).mark_line().encode(
x='timestamp:T',
y='data:Q',
color='id:N',
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.