【问题标题】:Converting nested dictionary to pandas dataframe and plotting将嵌套字典转换为 pandas 数据框并绘图
【发布时间】:2021-06-30 05:33:04
【问题描述】:

我有一个监听器,它以以下方式不断记录收到的消息 --

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)

可以假设时间戳和数据都是浮点数。

对于单个 id,我可以使用 --

绘制数据
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)

这会产生一个数据框和图表:

所以我的问题是,我将如何备份一个关卡并从字典 listener.recorded 生成一个数据框/绘图,以便每个唯一的 id 都正确地绘制一个图例?我自己似乎无法完全到达那里......

【问题讨论】:

标签: python pandas altair streamlit


【解决方案1】:

您可以使用pd.concat 创建数据框,重置索引,然后照常使用 Altair。这是一个简短的示例,其中的数据类似于您正在生成的字典:

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',
)

【讨论】:

  • 正是我想要的。非常感谢!
猜你喜欢
  • 2021-11-28
  • 2022-01-07
  • 2015-10-06
  • 2021-12-21
  • 2018-06-03
  • 1970-01-01
  • 2014-05-10
  • 1970-01-01
相关资源
最近更新 更多