I wrote this code so that I can select a particular class from a drop-down and then display a filtered df which shows all the instances where the ground truth is the selected class, but the prediction is some other class.
from IPython.display import display
class_selector = widgets.Dropdown(options=class_labels)
display_button = widgets.Button(description='Display')
def on_display_button_clicked(b):
filtered_df = df[(df["Model_GroundTruth"] == class_selector.value) &(df["Model_Prediction"] != class_selector.value)]
display(filtered_df)
display_button.on_click(on_display_button_clicked)
display(class_selector)
display(display_button)
I am running this in a notebook and filtered_df is being displayed in the notebook logs, not the notebook itself. Can someone please tell me what is missing
Related
Python 3.8.10
Ubuntu 20.04
Using st_aggrid (the Python port of AgGrid for Streamlit.)
Streamlit allows for layout control using st.column, st.empty, and st.container. The format is (for example)...
col1, col2 = st.columns(2)
original = Image.open(image)
col1.header("Original")
col1.image(original, use_column_width=True)
grayscale = original.convert('LA')
col2.header("Grayscale")
col2.image(grayscale, use_column_width=True)
Notice that col1 and col2 replace the st. in all the commands.
I.e. without columns it would be...
import streamlit as st
original = Image.open(image)
st.header("Original")
st.image(original, use_column_width=True)
grayscale = original.convert('LA')
st.header("Grayscale")
st.image(grayscale, use_column_width=True)
...and things would all just appear one on top of the other on the page.
st_aggrid Grid's are created and placed using the command ...
instruments_gb = GridOptionsBuilder.from_dataframe(instruments_df)
if st.session_state["enable_sidebar"]:instruments_gb.configure_side_bar()
instruments_gb.configure_selection(st.session_state["selection_mode"])
instruments_gb.configure_selection(st.session_state["selection_mode"], use_checkbox=True, groupSelectsChildren=st.session_state["groupSelectsChildren"], groupSelectsFiltered=st.session_state["groupSelectsFiltered"])
instruments_gb.configure_selection(st.session_state["selection_mode"], use_checkbox=False, rowMultiSelectWithClick=True, suppressRowDeselection=True)
instruments_gb.configure_grid_options(domLayout='normal')
instruments_gridOptions = instruments_gb.build()
AgGrid(
instruments_df,
gridOptions=instruments_gridOptions,
height=st.session_state["grid_height"],
width='100%',
data_return_mode=st.session_state["return_mode_value"],
update_mode=st.session_state["update_mode_value"],
fit_columns_on_grid_load=True,
allow_unsafe_jscode=True, #Set it to True to allow js function to be injected
enable_enterprise_modules=True,
)
This will create and display the Grid. Note that st. is not used anywhere within the commands.
How can I place an st_aggrid Grid inside a Streamlit
container/placeholder?
Alternatively, can the Grid be placed in a
specific location on the page, without using Streamlit containers?
Here is an example on how to place aggrid inside the container.
import streamlit as st
import numpy as np
from st_aggrid import AgGrid
import pandas as pd
data = {
'country': ['norway', 'russia', 'china', 'japan'],
'capital': ['oslo', 'moscow', 'beijing', 'tokyo']
}
df = pd.DataFrame(data)
with st.container():
st.write("This is inside the container")
AgGrid(df, height=200)
st.bar_chart(np.random.randn(50, 3))
st.write("This is outside the container.")
Output
I have the following query in Excel using BQL:
=BQL("MEMBERS('INEMCBI LX Equity',type=holdings)";"name";"cols=2;rows=223")
This shows a table of securities of a specific mutual fund. Like this:
enter image description here
I want to get the same information using python in Dataframe structure but I dont know any way to get it.
If you run BQNT<GO> on the terminal, you'll get access to Python BQL examples, but the examples won't work outside of BQNT. Since you mention using =BQL, I'm assuming you have access to a terminal.
Example in BQNT:
import bql
bq = bql.Service()
fund = bq.univ.members("INEMCBI LX Equity", type="HOLDINGS")
name = bq.data.name()
req = bql.Request(fund, {"Fund Holdings": name})
res = bq.execute(req)
data = res[0].df()
data
Run BQNT on your Bloomberg terminal to ensure the BQL environment is installed.
Follow the steps exactly as followed.
Open file explorer
Navigate to C:\blp\bqnt\environments\bqnt-3\Lib\site-packages and copy these folders:
bqapi
bqbreg
bql
bqlmetadata
bqrequest
bqutil
ciso8601
Paste them to your python installation folder %userprofile%\Anaconda3\envs{mypythonenv}\lib\site-packages\
Then you can test this code in your code editor. I use Vscode.
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt
import bql
bq = bql.Service()
query = """get(px_last)for('AAPL US EQUITY')with(dates=range(-1y,0d),fill='prev')"""
data = bql.combined_df(bq.execute(query)).reset_index()
fig = plt.figure(figsize=(12,8))
sb.lineplot(data=data, x='DATE',y='px_last')
plt.show()
I have explored the available methods of how to render a gltf/glb file inline in a jupyter notebook to keep the viewer callback interactivity intact. I have eventually ended up using vtk and k3d to achieve this. The two hurdles I have are:
How to use the vtkGLTFReader() to get vtkPolyData objects from the
glb and render these in k3d? SOLUTION: See method posted in the comments.
How to display colors/textures embedded in the gltf/glb to show them in
k3d?
Here is the code to get vtkPolyData and pass it to k3d.
import k3d
import vtk
import ipywidgets as widgets
reader = vtk.vtkGLTFReader()
reader.SetFileName('sample_glb/GroundVehicle.glb')
reader.Update()
plot = k3d.plot()
mb = reader.GetOutput()
iterator = mb.NewIterator()
vtk_polyobjects = []
while not iterator.IsDoneWithTraversal():
item = iterator.GetCurrentDataObject()
vtk_polyobjects.append(item)
iterator.GoToNextItem()
for obj in vtk_polyobjects:
plot += k3d.vtk_poly_data(obj, color=0x222222)
plot.display()
debug_info = widgets.HTML()
I am using Jupyter notebook with Python 3 kernel. I have a computation which bases on user input by an IPython widget.
The result of the computation needs to be shown in a markdown cell. For this I use the Python Markdown nbextension. The Question now is: How do I update the markdown cell on user interaction?
I tried to run the markdown cell from python using a Javascript call.
As a minimal example, the following two cells may serve. (First normal python cell, second markdown cell)
from IPython.display import Javascript
import ipywidgets
def update_md_cell(slider_value):
Javascript("Jupyter.notebook.execute_cells([1])")
t_slider = ipywidgets.IntSlider(min = 0, max = 10, value = 10)
ipywidgets.interactive(update_md_cell, slider_value = t_slider)
... The value of number is {{t_slider.value}}. ...
But this seems to work only outside of functions.
Javascript("Jupyter.notebook.execute_cells ([1])")
reloads the markdown cell.
def update_md_cell():
Javascript("Jupyter.notebook.execute_cells ([1])")
update_md_cell()
does nothing.
Is there another way to connect the inputs (through the IPython widget) to the output (in the Markdown cell)?
Update: Like mentioned in the comment to Suraj Potnuru's answer, my basic problem is the gotcha from here:
A big gotcha: something somewhere needs to return Javascript as its output, otherwise it doesn’t get executed in the notebook.
But it's even worse, a return in the via ipywidgets.interactive() binded function is not enough to fix the gotcha, e.g.:
def update_md_cell():
return Javascript("Jupyter.notebook.execute_cells ([1])")
update_md_cell()
works.
from IPython.core.display import Javascript
from IPython.display import display
import ipywidgets
def update_md_cell(slider_value):
return Javascript("Jupyter.notebook.execute_cells ([1])")
t_slider = ipywidgets.IntSlider(min = 0, max = 10, value = 10)
ipywidgets.interactive(update_md_cell, slider_value = t_slider)
doesn't work.
How do I get the second to work?
Update your foo() function to the below code
def foo():
slider_value = t_slider.value
display(Javascript("var markdown_cell = IPython.notebook.get_cell(1);markdown_cell.set_text('The value of the number is "+ str(slider_value) +"');IPython.notebook.execute_cell(1)"))
The above code snippet fetches the value of the slider object and uses get_cell() function to fetch the first cell which is your markdown cell. The cells numbering starts from 0, hence 0th cell is your python code cell, 1st cell is your markdown cell.
It uses the set_text() function to update the markdown inside your cell with the latest slider value.
Call foo() function whenever your slider is updated to update the markdown also.
I am using Python3.4.2 and pythonOCC-0.16.0-win32-py34.exe to draw components. Every components are rendered properly with one defined color but that is not look like a real world component.
Above image is my Python implementation which generate 3D image from STEP file with one color.
Below image is rendered one of my windows software and there I have used Step file. I want to render component same as look like in below image so its look like a real world component.
Is there any way to get correct colored output in Python by read STEP file? I have searched a lot but didn't get a way to implement it. Please help me to go in forward direction.
from future import print_function
import sys
#from OCC.STEPCAFControl import STEPCAFControl_Reader
from OCC.STEPControl import STEPControl_Reader
from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity
from OCC.Display.SimpleGui import init_display
from OCC.Display.WebGl import threejs_renderer
step_reader = STEPControl_Reader()
status = step_reader.ReadFile('./models/test.STEP')
if status == IFSelect_RetDone: # check status
failsonly = False
step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)
ok = step_reader.TransferRoot(1)
_nbs = step_reader.NbShapes()
aResShape = step_reader.Shape(1)
else:
print("Error: can't read file.")
sys.exit(0)
#display, start_display, add_menu, add_function_to_menu = init_display()
#display.DisplayShape(aResShape, update=True)
#start_display()
my_renderer = threejs_renderer.ThreejsRenderer(background_color="#123345")
my_renderer.DisplayShape(aResShape)
The above code is used for read STEP file using Python.