python - 如何更改数据框中的不同值
问题描述
每个品牌都有不同的类别。我需要一个显示不同品牌的按钮。如果我单击该品牌,例如 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'}}
解决方案
# 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
推荐阅读
- android - 如何让我的报警服务在后台运行?
- javascript - 打印 HTML 内容
- sql - 以sql的日期格式转换插入的字符串
- sql - 访问将多条记录链接到同一条记录
- linux - Linux 命令在 Ansible 的特定输出中获取用户及其组
- java - SL4J 配置更改或正则表达式以屏蔽 Json 中的电子邮件(由 '@' 和 '.com' 识别)
- stream - Flutter 中的 Sink 和 Stream 有什么区别?
- hibernate - 常量作为 NamedQueries 中的参数是一个好习惯吗?
- ruby-on-rails - Rails 4 + Google:在网页上显示评论
- react-native - 反应原生和领域同步