ipython-books / cookbook-code Goto Github PK
View Code? Open in Web Editor NEW[DEPRECATED] See the new edition:
Home Page: http://ipython-books.github.io/
License: Other
[DEPRECATED] See the new edition:
Home Page: http://ipython-books.github.io/
License: Other
FWIW, if users have problems with ipywidgets there appears to be a bigger issue with ipywidgets not working in latest v.
jupyter-widgets/ipywidgets#669 (comment)
I did manage to get ipywidgets to run using:
~/.local/bin/jupyter nbextension enable --py widgetsnbextension
and then
~/.local/bin/jupyter notebook
I hope the above helps someone.
prettyplotlib is covered in recipe 6.1. However, Olga Botvinnik (@olgabot) is no longer actively developing this library.
If you are interested in similar features for improving matplotlib's styling, you can:
Greetings Cyrille,
I was able to replicate recipe 6.4: 'Visualizing a NetworkX graph in the IPython notebook with DJ.js' successfully except for getting the node labels to display. The recipe claims one can click on the nodes to see their labels. Any advice for how to get this to work? The help would be appreciated.
May need to tweak a few examples with custom widgets in the notebook to make them work with IPython 2.x (see this issue in IPython).
the memory mapping exemple will only work if the file already exists.
to make it work regardless of that, it should have the mode parameter filled:
f = np.memmap('memmapped.dat', dtype=np.float32, mode='w+', shape=(nrows, ncols))
seaborn.corrplot(df);
should now be
seaborn.heatmap(df);
as per
https://stanford.edu/~mwaskom/software/seaborn/whatsnew.html?highlight=corrplot
In the 6th python cell:
program['a_position'] = np.c_[
np.linspace(-1.0, +1.0, 1000),
np.random.uniform(-0.5, +0.5, 1000)]
results in:
TypeError: data must be 32-bit not float64
I may mess with this later, but I know next to nothing about vispy so I'm not sure how well I can troubleshoot the issue.
when i start notebook, there's a error in my console as follow
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/notebook/base/handlers.py", line 437, in wrapper
result = yield gen.maybe_future(method(self, *args, **kwargs))
File "/Library/Python/2.7/site-packages/notebook/services/sessions/handlers.py", line 56, in post
model = sm.create_session(path=path, kernel_name=kernel_name)
File "/Library/Python/2.7/site-packages/notebook/services/sessions/sessionmanager.py", line 66, in create_session
kernel_name=kernel_name)
File "/Library/Python/2.7/site-packages/notebook/services/kernels/kernelmanager.py", line 84, in start_kernel
**kwargs)
File "/Library/Python/2.7/site-packages/jupyter_client/multikernelmanager.py", line 109, in start_kernel
km.start_kernel(**kwargs)
File "/Library/Python/2.7/site-packages/jupyter_client/manager.py", line 244, in start_kernel
**kw)
File "/Library/Python/2.7/site-packages/jupyter_client/manager.py", line 190, in _launch_kernel
return launch_kernel(kernel_cmd, **kw)
File "/Library/Python/2.7/site-packages/jupyter_client/launcher.py", line 124, in launch_kernel
proc = Popen(cmd, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
how can I fix it ?
my mac's info:
Every recipe ends with a footer:
You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).
Since the book has been already published, I suggest changing it to a link to the book description/publication info.
Posted by Anand Muglikar.
I used the ipython notebook shown below which uses your code as a base:
On running the code, webcam opens but no video is seen on Iceweasel browser (firefox based). On Chrome, webcam just starts and immediately shuts. I'm a newbie in Python and do not know javascript. Please guide.
Thanks in advance! :)
It is a page about the computer game Dweep.
see also ipython/ipython#7869
Thanks for writing the cookbook and sharing it online. This is certain to become a great resource for our users.
In cookbook 01_numpy_performance, it is recommended to use x.__array_interface__['data'][0]
to determine if an array is sharing data with another array. This is only useful if the offset of the arrays are the same, not if one array is a subarray/slice/view of another.
For example, here, two arrays are sharing the same data but they have different starting pointers.
In [1]: import numpy as np
In [2]: x = np.arange(10)
In [3]: y = x[1::2]
In [4]: x.__array_interface__['data'][0]
Out[4]: 46090608
In [5]: y.__array_interface__['data'][0]
Out[5]: 46090616
You could probably figure out that their data areas are overlapping, but that’s kind of expensive/complex.
The best way I’ve found to find out if two arrays share the same data:
def get_data_base(arr):
base = arr.base
while base is not None:
base = base.base
return base
>>> get_data_base(x) is get_data_base(y)
True
A few issues:
Step 2: make sure to actually use "g = nx.read_shp("data/tl_2013_06_prisecroads.shp", simplify =False)". Without setting simplify to False, grid-like road structures become completely broken graphs. This is extremely important when using open street map data for example.
Step 3: to get the maximally connected subgraph, use the command 'max(nx.connected_component_subgraphs(g.to_undirected()), key=len)'
Step 7: Since the "JSON" coordinates are in the form (lon,lat), you are actually passing the wrong set to the geocalc function. Change to 'return np.sum(geocalc(path[1:,1],path[1:,0],path[:-1,1],path[:-1,0]))'. Surprisingly, the path it finds is nearly the same, and the distance is only a bit different.
One of the featured recipes is this nice energy-minimization problem. But I think the final plot is missing some really interesting features. In particular, the function that plots the spring bar contains the line
color=plt.cm.copper(c*150))
This means that negative values (corresponding to compression of the spring, rather than extension) don't get any special coloring -- they get chopped. If you allow for negative values, you can see those compressed springs:
You can see that the lower springs near the wall are very compressed, and the diagonal ones get some compression as well. I think that's too interesting to ignore! :)
The simplest way to deal with this would just be
color=plt.cm.copper(abs(c*150)))
But that wouldn't show you which springs are compressed and which are extended. To get the plot above, I defined a new color function
def spring_color_map(c):
min_c, max_c = -0.00635369422326, 0.00836362559722
ratio = (max_c-c) / (max_c-min_c)
color = plt.cm.coolwarm(ratio)
shading = np.sqrt(abs(ratio-0.5)*2)
return (shading*color[0], shading*color[1], shading*color[2], color[3])
and then in the plotting function, I did
color=spring_color_map(c)
AttributeError Traceback (most recent call last)
in ()
----> 1 c.show()
2 app.run();
f:\anaconda3\vispy-master\vispy\app\canvas.py in show(self, visible, run)
427 Run the backend event loop.
428 """
--> 429 self._backend._vispy_set_visible(visible)
430 if run:
431 self.app.run()
f:\anaconda3\vispy-master\vispy\app\backends_ipynb_webgl.py in _vispy_set_visible(self, visible)
206 return
207 if self._widget is None:
--> 208 self._widget = VispyWidget()
209 self._widget.set_canvas(self._vispy_canvas)
210 display(self._widget)
f:\anaconda3\vispy-master\vispy\app\backends\ipython_widget.py in init(self, **kwargs)
60 def init(self, **kwargs):
61 super(VispyWidget, self).init(**kwargs)
---> 62 self.on_msg(self.events_received)
63 self.canvas = None
64 self.canvas_backend = None
AttributeError: 'VispyWidget' object has no attribute 'on_msg'
error on running the first cell:
ShimWarning: The IPython.html
package has been deprecated. You should import from notebook
instead. IPython.html.widgets
has moved to ipywidgets
.
"IPython.html.widgets
has moved to ipywidgets
.", ShimWarning)
/home/dgd/.local/lib/python3.5/site-packages/IPython/utils/traitlets.py:5: UserWarning: IPython.utils.traitlets has moved to a top-level traitlets package.
warn("IPython.utils.traitlets has moved to a top-level traitlets package.")
Run pd.rolling_mean(df['Berri1'], n).dropna().plot();
and you get
/usr/local/lib/python2.7/dist-packages/ipykernel/__main__.py:6: FutureWarning: pd.rolling_mean is deprecated for Series and will be removed in a future version, replace with
Series.rolling(window=15,center=False).mean()
How can you do the replacement with Series.rolling(...).mean()
?
walked through the demo but got a fail mid way through
!nosetests
/bin/sh: 1: nosetests: not found
The notebook should have a sanity check to see if nose is installed at all... I've created a sample and attached same.
updaedwithnoseinsallcheck07_unittests.ipynb.zip
I've just installed bokeh 0.8.2 (the version pip finds). The 'line' and 'scatter' functions are now methods of a figure object, so in notebook chapter06/03_bokeh I had to change the first example to:
p = bkh.figure(title="random data", x_axis_label='x', y_axis_label='y')
p.line(x, y, line_width=5)
bkh.show(p)
and the second to:
p = bkh.figure(title="flower petal shapes by color", x_axis_label='petal_length', y_axis_label='petal_width')
p.scatter(flowers["petal_length"],
flowers["petal_width"],
color=flowers["color"],
fill_alpha=0.25, size=10,)
bkh.show(p)
As reported by one user:
Page: 19 & 20
In the example that begins:
"10. Now, we illustrate the latest interactive features in IPython 2.0+,
namely JavaScript widgets."
I had to change the world 'values' to 'options' in
dw = DropdownWidget(values=OrderedDict([
and
dw.value = dw.values['SciPy 2013'].
Using IPython 3.1.0, Python 2.7.9.
This issue is to track progress of the upgrade and discuss problems along the way, if any.
TODO:
Also:
Chapter 1 Recipe 2 (pandas demonstration) contains a link to a CSV dataset that seems not to be available online:
http://donnees.ville.montreal.qc.ca/storage/f/2014-01-20T20%3A48%3A50.296Z/2013.csv
Maybe host the data on GitHub instead and use a link to the raw file content?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.