首页 > 解决方案 > 如何更改数据框中的不同值

问题描述

我有一个看起来像这样的数据框: 在此处输入图像描述

每个品牌都有不同的类别。我需要一个显示不同品牌的按钮。如果我单击该品牌,例如 bmw,我会在折线图中显示 4 个不同的类别。x 轴是日期,y 轴是价格,线条的颜色按该品牌内的类别显示。这是数据框。这些只是许多值中的 5 个

{'Date': {0: Timestamp('2020-03-18 00:00:00'),
  1: Timestamp('2020-03-18 00:00:00'),
  2: Timestamp('2020-03-18 00:00:00'),
  3: Timestamp('2020-03-18 00:00:00'),
  4: Timestamp('2020-03-18 00:00:00')},
 'price': {0: 281435.0, 1: 102577.0, 2: 204844.0, 3: 271199.0, 4: 144790.0},
 'Brand': {0: 'bmw', 1: 'ford', 2: 'hyundai', 3: 'mercedes-benz', 4: 'nissan'},
 'category': {0: 'bmw_5 series_executive_2016',
  1: 'ford_focus_trend x_2015',
  2: 'hyundai_tucson_elite plus_2017',
  3: 'mercedes-benz_e-class_edition e_2015',
  4: 'nissan_qashqai_black edition_2014'}}

标签: pythonpandasplotly

解决方案


# imports

from jupyter_dash import JupyterDash 
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd

# app
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = JupyterDash(__name__, external_stylesheets=external_stylesheets)

server = app.server

brands = df['Brand'].unique()  ## get unique brands for dropdown

app.layout = html.Div([
    html.Div(dcc.Dropdown(
            id='filter-brands',
            options=[{'label': i, 'value': i} for i in brands],
            value='bmw'
        ), 
         style={'display': 'inline-block',
                'width': "100%",
                'borderBottom': 'thin lightgrey solid',
                'backgroundColor': 'rgb(250, 250, 250)',
                'padding': '10px 5px'}),
    html.Div(dcc.Graph(
            id='categories-timeseries'
        ))
])

# to create timeseries chart on update
def create_time_series(dff):
    return px.line(dff, x="Date", y="price", color='category')


@app.callback(
    dash.dependencies.Output('categories-timeseries', 'figure'),
    dash.dependencies.Input('filter-brands', 'value'))
def update_timeseries(brand):
    dff = df[df['Brand'] == brand].sort_values("Date")
    return create_time_series(dff)


app.run_server(mode="jupyterlab")

或使用

app.run_server() ## to open in browser

在此处输入图像描述


推荐阅读