Dash 在回调中动态更新 AG 网格单元格

问题描述 投票:0回答:1
我正在寻求一些帮助,了解如何在 Dash 应用程序中保留原始数据帧值,同时允许用户通过手动单元格编辑或使用滑块将列中的所有值进行倍增来动态修改 AG Grid 中的单元格值。下面提供了一个最小的示例。

我遇到的问题是,当用户调整滑块时,它会覆盖表值,这是预期的,但每次调整滑块时,值都会不断增加..我需要的是保持原始值- 即使用户手动在单元格中输入新值 - 滑块也会对这些新值进行操作。

df = pd.read_csv('sample_data.csv') # make a copy of the origina column so the user can make edits: called "Planner" df['Planner'] = df['Predictions'] @app.callback( Output('pred_grid', 'rowData'), Output('pred_grid', 'columnDefs'), Input('slider_multiplier', 'value'), # slider to allow the user to make adjustments on all values at once Input("pred_grid", "cellValueChanged"), State('pred_grid', 'rowData') ) def make_grid(slider, cell_chng, row_cng): button_id = ctx.triggered_id if not None else 'No clicks yet' cols = [{"field": i} for i in df.columns] # This condition works correctly. if not cell_chng: planner_preds = df['Predictions'].values r = df.copy() if not button_id == 'slider_multiplier': r2 = df.to_dict('records') else: t = planner_preds mlt = np.repeat(slider, len(t)) r['Planner'] = np.round(df['Predictions']*(1+mlt),0) r2 = r.to_dict("records") # This condition fails because if I manually edit he cell value, then try to move the slider, the original values keep getting updated, so moving the slider keeps increasing the values indefinitely. # What I expect to happen is that when I edit the cells directly, the new values are used as the base values for when the slider is then used for multiplication. So, when the user moves the slider up all the values are multiplied (i.e. 34*(1.05)), but when the user moves the slider back down the same base values are used for that calculation. Instead what's happening is that the slider multiplies the values, then updates the row data, which is then used to multiply new values... so, it's always increasing. I can't seem to figure out how to make this work as expected... else: # This part works if not button_id == 'slider_multiplier': r2 = pd.DataFrame(row_cng, columns=[i for i in df.columns]) r2 = r2.to_dict("records") # This part does not work because row_cng is always updated in the callback; I need to hold the original values, or manually edited values constant else: r2 = pd.DataFrame(row_cng, columns=[i for i in df.columns]) t = [int(i) for i in r2['Planner']] mlt = np.repeat(slider, len(t)) r2['Planner'] = np.round(t*(1+mlt),2) r2 = r2.to_dict("records") return r2, cols
图片展示了这个想法。  我可以通过双击手动编辑这些单元格值。  没问题。  但如果我尝试使用滑块,它会保留修改后的值,并且该修改后的值将成为下次移动滑块时的新“基”值。  我想在调整滑块(乘数)时保留原始基值。  例如,在此示例中,我将滑块向上移动到 0.5,值 23 乘以 1.5,即变为 34.5。  如果我再次移动滑块说 0.2,则 34.5 乘以 1.2...这是错误的,我希望 23 乘以 1.2。  如果我手动将 23 更改为 5,那么我希望将相同的逻辑应用于 5,而不是 23。

enter image description here

感谢您提供的任何帮助!

python ag-grid plotly-dash
1个回答
0
投票
使用 dcc.Store 对象将原始数据帧存储为 JSON 对象。使用带有商店和滑块的回调作为输入,计算最终的数据帧应该是什么,并使用它来创建网格。

Dash 核心组件 - dcc.Store 文档

© www.soinside.com 2019 - 2024. All rights reserved.