技术咨询:合并.ipynb为.py模块、导入.ipynb到.py及展示可视化图表
Hey there! Let's break down each of your questions with practical, actionable steps since you're working on combining Jupyter notebooks and Python modules for your data visualization work:
1. Merging multiple .ipynb files into a single .py module
The easiest way to start is by converting each notebook to a Python script first, then combining the relevant code into one module. Here's how:
Convert individual notebooks to .py: Use Jupyter's built-in
nbconverttool from the command line:jupyter nbconvert --to script notebook1.ipynb jupyter nbconvert --to script notebook2.ipynbThis will generate
notebook1.pyandnotebook2.pyfiles in the same directory.Clean and combine the scripts: Open the generated .py files and remove any Jupyter-specific code (like
get_ipython().run_line_magic('matplotlib', 'inline')or unused cell outputs). Then copy the functions, classes, and code snippets you need into a single.pyfile (e.g.,my_visualization_module.py).Optional batch conversion: If you have many notebooks, you can automate the conversion with a small Python script:
import os from nbconvert import PythonExporter import nbformat def convert_notebook_to_py(notebook_path): with open(notebook_path, 'r', encoding='utf-8') as f: nb = nbformat.read(f, as_version=4) exporter = PythonExporter() source, _ = exporter.from_notebook_node(nb) py_path = os.path.splitext(notebook_path)[0] + '.py' with open(py_path, 'w', encoding='utf-8') as f: f.write(source) # Convert all .ipynb files in the current directory for file in os.listdir('.'): if file.endswith('.ipynb'): convert_notebook_to_py(file)
2. Importing a .ipynb file directly into a .py module
If you don't want to convert the notebook first, you can use the import-ipynb library to import notebooks directly:
Install the library:
pip install import-ipynbImport the notebook in your .py file:
import import_ipynb # Now you can import the notebook like a regular module import my_data_notebookNote: Make sure the
.ipynbfile is in the same directory as your .py script, or in a directory listed insys.path. Also, remove any interactive cell outputs or magic commands from the notebook to avoid import errors.
3. Displaying data visualization charts in a .py module
The approach depends on which visualization library you're using. Here are the most common scenarios:
Matplotlib/Seaborn
In Jupyter notebooks, you might use %matplotlib inline to display charts, but in a .py module, you need to explicitly call plt.show():
import matplotlib.pyplot as plt import seaborn as sns # Sample visualization data = [1, 3, 5, 7, 9] sns.lineplot(x=range(len(data)), y=data) # Call show() to display the chart plt.show()
If you're running the script on a server without a GUI, you can save the chart to a file instead:
plt.savefig('my_chart.png')
Plotly
For interactive Plotly charts, use plotly.io.show() to display the chart in your default browser:
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length") # Display the interactive chart import plotly.io as pio pio.show(fig)
Alternatively, you can save it as an HTML file for sharing:
fig.write_html('interactive_chart.html')
Bokeh
For Bokeh visualizations, use show() from bokeh.io:
from bokeh.plotting import figure, show from bokeh.io import output_notebook # Create a plot p = figure(title="Sample Bokeh Plot") p.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5]) # Display the plot in a browser tab show(p)
内容的提问来源于stack exchange,提问作者VEERESH NB

