标签归档:jupyter

将图像插入IPython Notebook Markdown

问题:将图像插入IPython Notebook Markdown

我开始严重依赖IPython Notebook应用程序来开发和记录算法。太棒了; 但是似乎有些应该可行的方法,但是我不知道该怎么做:

我想在我的(本地)IPython笔记本降价中插入本地图像,以帮助记录算法。我知道足够<img src="image.png">在降价中添加类似内容,但据我所知。我假设我可以将图像放在127.0.0.1:8888表示的目录(或某些子目录)中,以便能够访问它,但是我不知道该目录在哪里。(我正在Mac上工作。)那么,是否可以在没有太多麻烦的情况下做我想做的事情?

I am starting to depend heavily on the IPython notebook app to develop and document algorithms. It is awesome; but there is something that seems like it should be possible, but I can’t figure out how to do it:

I would like to insert a local image into my (local) IPython notebook markdown to aid in documenting an algorithm. I know enough to add something like <img src="image.png"> to the markdown, but that is about as far as my knowledge goes. I assume I could put the image in the directory represented by 127.0.0.1:8888 (or some subdirectory) to be able to access it, but I can’t figure out where that directory is. (I’m working on a mac.) So, is it possible to do what I’m trying to do without too much trouble?


回答 0

笔记本目录中的文件位于“ files /” URL下。因此,如果它位于基本路径中,则为<img src="files/image.png">,子目录等也可用:<img src="files/subdir/image.png">,等等。

更新:从IPython 2.0开始,files/不再需要该前缀(请参阅发行说明)。因此,现在该解决方案<img src="image.png">可以按预期工作。

Files inside the notebook dir are available under a “files/” url. So if it’s in the base path, it would be <img src="files/image.png">, and subdirs etc. are also available: <img src="files/subdir/image.png">, etc.

Update: starting with IPython 2.0, the files/ prefix is no longer needed (cf. release notes). So now the solution <img src="image.png"> simply works as expected.


回答 1

到目前为止,大多数给出的答案都是错误的,建议加载其他库并使用代码而不是标记。在Ipython / Jupyter Notebooks中,这非常简单。确保单元格确实在标记中并显示图像以供使用:

![alt text](imagename.png "Title")

与建议的其他方法相比,进一步的优点是您可以显示所有常见的文件格式,包括jpg,png和gif(动画)。

Most of the answers given so far go in the wrong direction, suggesting to load additional libraries and use the code instead of markup. In Ipython/Jupyter Notebooks it is very simple. Make sure the cell is indeed in markup and to display a image use:

![alt text](imagename.png "Title")

Further advantage compared to the other methods proposed is that you can display all common file formats including jpg, png, and gif (animations).


回答 2

我正在使用ipython 2.0,所以只有两行。

from IPython.display import Image
Image(filename='output1.png')

I am using ipython 2.0, so just two line.

from IPython.display import Image
Image(filename='output1.png')

回答 3

[过时]

IPython / Jupyter现在支持扩展模块,该模块可以通过复制和粘贴或拖放来插入图像。

https://github.com/ipython-contrib/IPython-notebook-extensions

拖放扩展似乎可以在大多数浏览器中使用

https://github.com/ipython-contrib/IPython-notebook-extensions/tree/master/nbextensions/usability/dragdrop

但是复制和粘贴仅适用于Chrome。

[Obsolete]

IPython/Jupyter now has support for an extension modules that can insert images via copy and paste or drag & drop.

https://github.com/ipython-contrib/IPython-notebook-extensions

The drag & drop extension seems to work in most browsers

https://github.com/ipython-contrib/IPython-notebook-extensions/tree/master/nbextensions/usability/dragdrop

But copy and paste only works in Chrome.


回答 4

将图像导入Jupyter NB比大多数人在这里提到的要简单得多。

1)只需创建一个空的Markdown单元。2)然后将图像文件拖放到空白的Markdown单元格中。

然后出现将插入图像的降价代码。

例如,下面以灰色突出显示的字符串将出现在Jupyter单元格中:

![Venus_flytrap_taxonomy.jpg](attachment:Venus_flytrap_taxonomy.jpg)

3)然后按Shift-Enter执行Markdown单元。然后,Jupyter服务器将插入图像,然后图像将出现。

我正在运行Jupyter笔记本服务器是:Windows 7上具有Python 3.7.0的5.7.4。

这是如此简单!

Getting an image into Jupyter NB is a much simpler operation than most people have alluded to here.

1) Simply create an empty Markdown cell. 2) Then drag-and-drop the image file into the empty Markdown cell.

The Markdown code that will insert the image then appears.

For example, a string shown highlighted in gray below will appear in the Jupyter cell:

![Venus_flytrap_taxonomy.jpg](attachment:Venus_flytrap_taxonomy.jpg)

3) Then execute the Markdown cell by hitting Shift-Enter. The Jupyter server will then insert the image, and the image will then appear.

I am running Jupyter notebook server is: 5.7.4 with Python 3.7.0 on Windows 7.

This is so simple !!


回答 5

我将IPython笔记本与图像放在同一文件夹中。我使用Windows。图像名称是“ phuong huong xac dinh.PNG”。

在Markdown中:

<img src="phuong huong xac dinh.PNG">

码:

from IPython.display import Image
Image(filename='phuong huong xac dinh.PNG')

I put the IPython notebook in the same folder with the image. I use Windows. The image name is “phuong huong xac dinh.PNG”.

In Markdown:

<img src="phuong huong xac dinh.PNG">

Code:

from IPython.display import Image
Image(filename='phuong huong xac dinh.PNG')

回答 6

首先确保您在ipython笔记本单元格中处于markdown编辑模型中

这是其他人提出的方法的替代方法<img src="myimage.png">

![title](img/picture.png)

如果标题丢失,它似乎也可以工作:

![](img/picture.png)

请注意,路径中不应包含任何引号。不知道这是否适用于带有空格的路径!

First make sure you are in markdown edit model in the ipython notebook cell

This is an alternative way to the method proposed by others <img src="myimage.png">:

![title](img/picture.png)

It also seems to work if the title is missing:

![](img/picture.png)

Note no quotations should be in the path. Not sure if this works for paths with white spaces though!


回答 7

Jupyter Notebook的最新版本本机接受图像的复制/粘贴

Last version of jupyter notebook accepts copy/paste of image natively


回答 8

如果要在Markdown单元中显示图像,请使用:

<img src="files/image.png" width="800" height="400">

如果要在“代码”单元格中显示图像,请使用:

from IPython.display import Image
Image(filename='output1.png',width=800, height=400)

If you want to display the image in a Markdown cell then use:

<img src="files/image.png" width="800" height="400">

If you want to display the image in a Code cell then use:

from IPython.display import Image
Image(filename='output1.png',width=800, height=400)

回答 9

在运行此代码之前,将默认块从“代码”更改为“ Markdown”:

![<caption>](image_filename.png)

如果图像文件在另一个文件夹中,则可以执行以下操作:

![<caption>](folder/image_filename.png)

Change the default block from “Code” to “Markdown” before running this code:

![<caption>](image_filename.png)

If image file is in another folder, you can do the following:

![<caption>](folder/image_filename.png)

回答 10

对于那些希望将图像文件放在Jupyter机器上的位置的人,以便可以从本地文件系统显示它。

我把我的mypic.png

/root/Images/mypic.png

(即Jupyter在线文件浏览器中显示的Images文件夹)

在这种情况下,我需要将以下行放入Markdown单元中,以使我的图片显示在记事本中:

![My Title](Images/mypic.png)

For those looking where to place the image file on the Jupyter machine so that it could be shown from the local file system.

I put my mypic.png into

/root/Images/mypic.png

(that is the Images folder that shows up in the Jupyter online file browser)

In that case I need to put the following line into the Markdown cell to make my pic showing in the notepad:

![My Title](Images/mypic.png)

回答 11

明克的答案是正确的。

但是,我发现这些图像在“打印视图”中显得不完整(在运行Chrome浏览器中IPython 0.13.2版的Anaconda发行版的Windows计算机上)

解决方法是使用 <img src="../files/image.png">

这使得图像可以在“打印视图”和普通的iPython编辑视图中正确显示。

更新:自从我升级到iPython v1.1.0以来,由于打印视图不再存在,因此不再需要这种解决方法。实际上,您必须避免这种解决方法,因为它会阻止nbconvert工具查找文件。

minrk’s answer is right.

However, I found that the images appeared broken in Print View (on my Windows machine running the Anaconda distribution of IPython version 0.13.2 in a Chrome browser)

The workaround for this was to use <img src="../files/image.png"> instead.

This made the image appear correctly in both Print View and the normal iPython editing view.

UPDATE: as of my upgrade to iPython v1.1.0 there is no more need for this workaround since the print view no longer exists. In fact, you must avoid this workaround since it prevents the nbconvert tool from finding the files.


回答 12

您可以在jupyter笔记本中使用“ pwd”命令查找当前工作目录,不带引号。

You can find your current working directory by ‘pwd’ command in jupyter notebook without quotes.


在ipython Notebook中测量单元执行时间的简单方法

问题:在ipython Notebook中测量单元执行时间的简单方法

除了单元的原始输出,我想花时间在单元执行上。

为此,我尝试了%%timeit -r1 -n1但它没有公开定义在单元格内的变量。

%%time 适用于仅包含1条语句的单元格。

In[1]: %%time
       1
CPU times: user 4 µs, sys: 0 ns, total: 4 µs
Wall time: 5.96 µs
Out[1]: 1

In[2]: %%time
       # Notice there is no out result in this case.
       x = 1
       x
CPU times: user 3 µs, sys: 0 ns, total: 3 µs
Wall time: 5.96 µs

最好的方法是什么?

更新资料

我已经在Nbextension中使用Execute Time了一段时间了。这太棒了。

I would like to get the time spent on the cell execution in addition to the original output from cell.

To this end, I tried %%timeit -r1 -n1 but it doesn’t expose the variable defined within cell.

%%time works for cell which only contains 1 statement.

In[1]: %%time
       1
CPU times: user 4 µs, sys: 0 ns, total: 4 µs
Wall time: 5.96 µs
Out[1]: 1

In[2]: %%time
       # Notice there is no out result in this case.
       x = 1
       x
CPU times: user 3 µs, sys: 0 ns, total: 3 µs
Wall time: 5.96 µs

What’s the best way to do it?

Update

I have been using Execute Time in Nbextension for quite some time now. It is great.


回答 0

使用单元魔术和Phillip Cloud在github上的此项目:

通过将其放在笔记本顶部或如果您始终希望默认情况下将其放在配置文件中来进行加载:

%install_ext https://raw.github.com/cpcloud/ipython-autotime/master/autotime.py
%load_ext autotime

如果加载,则后续单元执行的每个输出将包括执行时间(以分钟和秒为单位)。

Use cell magic and this project on github by Phillip Cloud:

Load it by putting this at the top of your notebook or put it in your config file if you always want to load it by default:

%install_ext https://raw.github.com/cpcloud/ipython-autotime/master/autotime.py
%load_ext autotime

If loaded, every output of subsequent cell execution will include the time in min and sec it took to execute it.


回答 1

我发现克服此问题的唯一方法是执行带有print的最后一条语句。

不要忘了单元魔术始于,%%行魔术始于%

%%time
clf = tree.DecisionTreeRegressor().fit(X_train, y_train)
res = clf.predict(X_test)
print(res)

请注意,在下一个单元格中将不考虑在单元格内执行的任何更改,这在存在管道时是很直观的:

The only way I found to overcome this problem is by executing the last statement with print.

Do not forget that cell magic starts with %% and line magic starts with %.

%%time
clf = tree.DecisionTreeRegressor().fit(X_train, y_train)
res = clf.predict(X_test)
print(res)

Notice that any changes performed inside the cell are not taken into consideration in the next cells, something that is counter intuitive when there is a pipeline:


回答 2

%time%timeit现在来IPython中的一部分内置的魔法命令

%time and %timeit now come part of ipython’s built-in magic commands


回答 3

一种更简单的方法是在jupyter_contrib_nbextensions软件包中使用ExecuteTime插件。

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
jupyter nbextension enable execute_time/ExecuteTime

An easier way is to use ExecuteTime plugin in jupyter_contrib_nbextensions package.

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
jupyter nbextension enable execute_time/ExecuteTime

回答 4

我只是%%time在单元格的开头添加了时间。您可以在Jupyter Spark群集/虚拟环境上使用相同的名称。只需%%time在单元格的顶部添加,您将获得输出。在使用Jupyter的Spark集群上,我将其添加到单元格的顶部,并得到如下输出:-

[1]  %%time
     import pandas as pd
     from pyspark.ml import Pipeline
     from pyspark.ml.classification import LogisticRegression
     import numpy as np
     .... code ....

Output :-

CPU times: user 59.8 s, sys: 4.97 s, total: 1min 4s
Wall time: 1min 18s

I simply added %%time at the beginning of the cell and got the time. You may use the same on Jupyter Spark cluster/ Virtual environment using the same. Just add %%time at the top of the cell and you will get the output. On spark cluster using Jupyter, I added to the top of the cell and I got output like below:-

[1]  %%time
     import pandas as pd
     from pyspark.ml import Pipeline
     from pyspark.ml.classification import LogisticRegression
     import numpy as np
     .... code ....

Output :-

CPU times: user 59.8 s, sys: 4.97 s, total: 1min 4s
Wall time: 1min 18s

回答 5

import time
start = time.time()
"the code you want to test stays here"
end = time.time()
print(end - start)
import time
start = time.time()
"the code you want to test stays here"
end = time.time()
print(end - start)

回答 6

您可以使用timeit魔术功能。

%timeit CODE_LINE

或在细胞上

%%timeit 

SOME_CELL_CODE

https://nbviewer.jupyter.org/github/ipython/ipython/blob/1.x/examples/notebooks/Cell%20Magics.ipynb检查更多IPython魔术函数

You can use timeit magic function for that.

%timeit CODE_LINE

Or on the cell

%%timeit 

SOME_CELL_CODE

Check more IPython magic functions at https://nbviewer.jupyter.org/github/ipython/ipython/blob/1.x/examples/notebooks/Cell%20Magics.ipynb


回答 7

这不是很漂亮,但没有额外的软件

class timeit():
    from datetime import datetime
    def __enter__(self):
        self.tic = self.datetime.now()
    def __exit__(self, *args, **kwargs):
        print('runtime: {}'.format(self.datetime.now() - self.tic))

然后,您可以像这样运行它:

with timeit():
    # your code, e.g., 
    print(sum(range(int(1e7))))

% 49999995000000
% runtime: 0:00:00.338492

This is not exactly beautiful but without extra software

class timeit():
    from datetime import datetime
    def __enter__(self):
        self.tic = self.datetime.now()
    def __exit__(self, *args, **kwargs):
        print('runtime: {}'.format(self.datetime.now() - self.tic))

Then you can run it like:

with timeit():
    # your code, e.g., 
    print(sum(range(int(1e7))))

% 49999995000000
% runtime: 0:00:00.338492

回答 8

有时,使用时单元格中的格式会有所不同print(res),但是jupyter / ipython带有display。请参阅下面有关使用熊猫的格式差异的示例。

%%time
import pandas as pd 
from IPython.display import display

df = pd.DataFrame({"col0":{"a":0,"b":0}
              ,"col1":{"a":1,"b":1}
              ,"col2":{"a":2,"b":2}
             })

#compare the following
print(df)
display(df)

display语句可以保留格式。

Sometimes the formatting is different in a cell when using print(res), but jupyter/ipython comes with a display. See an example of the formatting difference using pandas below.

%%time
import pandas as pd 
from IPython.display import display

df = pd.DataFrame({"col0":{"a":0,"b":0}
              ,"col1":{"a":1,"b":1}
              ,"col2":{"a":2,"b":2}
             })

#compare the following
print(df)
display(df)

The display statement can preserve the formatting.


回答 9

您可能还需要查看python的分析魔术命令%prun,该命令给出类似以下内容的信息-

def sum_of_lists(N):
    total = 0
    for i in range(5):
        L = [j ^ (j >> i) for j in range(N)]
        total += sum(L)
    return total

然后

%prun sum_of_lists(1000000)

将返回

14 function calls in 0.714 seconds  

Ordered by: internal time      

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    5    0.599    0.120    0.599    0.120 <ipython-input-19>:4(<listcomp>)
    5    0.064    0.013    0.064    0.013 {built-in method sum}
    1    0.036    0.036    0.699    0.699 <ipython-input-19>:1(sum_of_lists)
    1    0.014    0.014    0.714    0.714 <string>:1(<module>)
    1    0.000    0.000    0.714    0.714 {built-in method exec}

当处理大量代码时,我发现它很有用。

you may also want to look in to python’s profiling magic command %prunwhich gives something like –

def sum_of_lists(N):
    total = 0
    for i in range(5):
        L = [j ^ (j >> i) for j in range(N)]
        total += sum(L)
    return total

then

%prun sum_of_lists(1000000)

will return

14 function calls in 0.714 seconds  

Ordered by: internal time      

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    5    0.599    0.120    0.599    0.120 <ipython-input-19>:4(<listcomp>)
    5    0.064    0.013    0.064    0.013 {built-in method sum}
    1    0.036    0.036    0.699    0.699 <ipython-input-19>:1(sum_of_lists)
    1    0.014    0.014    0.714    0.714 <string>:1(<module>)
    1    0.000    0.000    0.714    0.714 {built-in method exec}

I find it useful when working with large chunks of code.


回答 10

遇到麻烦时,意味着什么:

?%timeit 要么 ??timeit

要获取详细信息:

Usage, in line mode:
  %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
or in cell mode:
  %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
  code
  code...

Time execution of a Python statement or expression using the timeit
module.  This function can be used both as a line and cell magic:

- In line mode you can time a single-line statement (though multiple
  ones can be chained with using semicolons).

- In cell mode, the statement in the first line is used as setup code
  (executed but not timed) and the body of the cell is timed.  The cell
  body has access to any variables created in the setup code.

When in trouble what means what:

?%timeit or ??timeit

To get the details:

Usage, in line mode:
  %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
or in cell mode:
  %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
  code
  code...

Time execution of a Python statement or expression using the timeit
module.  This function can be used both as a line and cell magic:

- In line mode you can time a single-line statement (though multiple
  ones can be chained with using semicolons).

- In cell mode, the statement in the first line is used as setup code
  (executed but not timed) and the body of the cell is timed.  The cell
  body has access to any variables created in the setup code.

回答 11

如果要打印壁单元执行时间,这是一个技巧,请使用

%%time
<--code goes here-->

但是请确保%% time是一个魔术函数,因此请将其放在代码的第一行

如果您将其放在代码的某些行之后,则会出现用法错误,并且无法正常工作。

If you want to print wall cell execution time here is a trick, use

%%time
<--code goes here-->

but here make sure that, the %%time is a magic function, so put it at first line in your code.

if you put it after some line of your code it’s going to give you usage error and not gonna work.


如何将文本文件(.py)加载/编辑/运行/保存到IPython Notebook单元中?

问题:如何将文本文件(.py)加载/编辑/运行/保存到IPython Notebook单元中?

我最近已将使用IPython笔记本作为工作流程的一部分。但是,我没有成功找到一种方法来将.py文件导入打开的IPython Notebook的各个单元中,以便可以对其进行编辑,运行和保存。能做到吗?

我在文档中找到了这一点,该文档告诉我如何将.py文件作为新笔记本导入,但是这与我想要实现的目标不符。

任何建议将不胜感激。

I’ve recently moved over to using IPython notebooks as part of my workflow. However, I’ve not been successful in finding a way to import .py files into the individual cells of an open IPython notebook so that they can edited, run and then saved. Can this be done?

I’ve found this in the documentation which tells me how to import .py files as new notebooks but this falls short of what I want to achieve.

Any suggestions would be much appreciated.


回答 0

编辑:从IPython 3(现在为Jupyter项目)开始,笔记本具有文本编辑器,可以用作加载/编辑/保存文本文件的更方便的替代方法。

可以使用magic命令将文本文件加载到笔记本单元中%load

如果执行包含以下内容的单元格:

%load filename.py

的内容filename.py将在下一个单元格中加载。您可以照常编辑和执行它。

要将单元格内容保存回文件中,请在单元格%%writefile filename.py的开头添加cell-magic 并运行它。请注意,如果已经存在同名文件,它将被静默覆盖

要查看任何魔术命令的帮助,请添加?:like %load?%%writefile?

有关魔术功能的常规帮助,请键入“%magic”。有关可用魔术功能的列表,请使用%lsmagic。对于其中任何一个的描述,请键入%magic_name ?,例如’%cd?’。

另请参见:官方IPython文档中的Magic函数

EDIT: Starting from IPython 3 (now Jupyter project), the notebook has a text editor that can be used as a more convenient alternative to load/edit/save text files.

A text file can be loaded in a notebook cell with the magic command %load.

If you execute a cell containing:

%load filename.py

the content of filename.py will be loaded in the next cell. You can edit and execute it as usual.

To save the cell content back into a file add the cell-magic %%writefile filename.py at the beginning of the cell and run it. Beware that if a file with the same name already exists it will be silently overwritten.

To see the help for any magic command add a ?: like %load? or %%writefile?.

For general help on magic functions type “%magic” For a list of the available magic functions, use %lsmagic. For a description of any of them, type %magic_name?, e.g. ‘%cd?’.

See also: Magic functions from the official IPython docs.


回答 1

写入/保存

%%writefile myfile.py

  • 将单元格内容写入/保存到myfile.py中(用于-a追加)。另一个别名:%%file myfile.py

跑步

%run myfile.py

  • 运行myfile.py并在当前单元格中输出结果

加载/导入

%load myfile.py

  • 将“导入” myfile.py加载到当前单元格中

寻求更多的魔术和帮助

%lsmagic

  • 列出所有其他酷单元魔术命令。

%COMMAND-NAME?

  • 获取有关如何使用特定命令的帮助。即%run?

注意

除了单元魔术命令之外,IPython Notebook(现在为Jupyter笔记本)非常酷,它允许您直接使用单元中的任何Unix命令(这也等同于使用%%bashcell magic命令)。

要从单元格运行unix命令,只需在命令前加上!标记。例如:

  • !python --version 查看您的python版本
  • !python myfile.py运行myfile.py并在当前单元格中输出结果,就像%run(请参阅!python%run下面的注释之间的区别)一样。

另外,请参阅此nbviewer以获取有关示例的进一步说明。希望这可以帮助。

To write/save

%%writefile myfile.py

  • write/save cell contents into myfile.py (use -a to append). Another alias: %%file myfile.py

To run

%run myfile.py

  • run myfile.py and output results in the current cell

To load/import

%load myfile.py

  • load “import” myfile.py into the current cell

For more magic and help

%lsmagic

  • list all the other cool cell magic commands.

%COMMAND-NAME?

  • for help on how to use a certain command. i.e. %run?

Note

Beside the cell magic commands, IPython notebook (now Jupyter notebook) is so cool that it allows you to use any unix command right from the cell (this is also equivalent to using the %%bash cell magic command).

To run a unix command from the cell, just precede your command with ! mark. for example:

  • !python --version see your python version
  • !python myfile.py run myfile.py and output results in the current cell, just like %run (see the difference between !python and %run in the comments below).

Also, see this nbviewer for further explanation with examples. Hope this helps.


回答 2

将一个Python文件拖放到Ipython笔记本的“ home”笔记本表中,单击“上传”。这将创建一个只有一个包含.py文件内容的单元格的新笔记本

从您喜欢的编辑器中进行其他复制/粘贴;)

Drag and drop a Python file in the Ipython notebooks “home” notebooks table, click upload. This will create a new notebook with only one cell containing your .py file content

Else copy/paste from your favorite editor ;)


回答 3

我发现在ipython笔记本中使用ls和cd查找文件是令人满意的。然后,在单元格中键入cat your_file_name,您将获得文件的内容,然后可以将其作为代码粘贴到单元格中。

I have found it satisfactory to use ls and cd within ipython notebook to find the file. Then type cat your_file_name into the cell, and you’ll get back the contents of the file, which you can then paste into the cell as code.


如何从本地计算机或Web资源将图像或图片嵌入jupyter笔记本中?

问题:如何从本地计算机或Web资源将图像或图片嵌入jupyter笔记本中?

我想将图像包括在Jupyter笔记本中。

如果我执行以下操作,则它会起作用:

from IPython.display import Image
Image("img/picture.png")

但是我想将图像包含在markdown单元格中,以下代码给出404错误:

![title]("img/picture.png")

我也试过

![texte]("http://localhost:8888/img/picture.png")

但是我仍然得到同样的错误:

404 GET /notebooks/%22/home/user/folder/img/picture.png%22 (127.0.0.1) 2.74ms referer=http://localhost:8888/notebooks/notebook.ipynb

I would like to include image in a jupyter notebook.

If I did the following, it works :

from IPython.display import Image
Image("img/picture.png")

But I would like to include the images in a markdown cell and the following code gives a 404 error :

![title]("img/picture.png")

I also tried

![texte]("http://localhost:8888/img/picture.png")

But I still get the same error :

404 GET /notebooks/%22/home/user/folder/img/picture.png%22 (127.0.0.1) 2.74ms referer=http://localhost:8888/notebooks/notebook.ipynb

回答 0

在markdown中,不得在图像文件名称的前后加上引号!

如果您仔细阅读错误消息,您将%22在链接中看到两个部分。那是html编码的引号。

你必须换线

![title]("img/picture.png")

![title](img/picture.png)

更新

假定您具有以下文件结构,并且您jupyter notebook在存储文件的目录example.ipynb(<-包含映像的标记)中运行 命令:

/
+-- example.ipynb
+-- img
    +-- picture.png

You mustn’t use quotation marks around the name of the image files in markdown!

If you carefully read your error message, you will see the two %22 parts in the link. That is the html encoded quotation mark.

You have to change the line

![title]("img/picture.png")

to

![title](img/picture.png)

UPDATE

It is assumed, that you have the following file structure and that you run the jupyter notebook command in the directory where the file example.ipynb (<– contains the markdown for the image) is stored:

/
+-- example.ipynb
+-- img
    +-- picture.png

回答 1

有几种方法可以在Jupyter笔记本中发布图像:

通过HTML:

from IPython.display import Image
from IPython.core.display import HTML 
Image(url= "http://my_site.com/my_picture.jpg")

您保留使用HTML标签调整大小等的功能。

Image(url= "http://my_site.com/my_picture.jpg", width=100, height=100)

您还可以通过相对或绝对路径显示本地存储的图像。

PATH = "/Users/reblochonMasque/Documents/Drawings/"
Image(filename = PATH + "My_picture.jpg", width=100, height=100)

如果图像宽于显示设置: 谢谢

用于unconfined=True禁用图像的最大宽度限制

from IPython.core.display import Image, display
display(Image('https://i.ytimg.com/vi/j22DmsZEv30/maxresdefault.jpg', width=1900, unconfined=True))

或通过降价:

  • 确保该单元格是降价单元格,而不是代码单元格,感谢@游凯超在评论中)
  • 请注意,在某些系统上,降价标记不允许在文件名中使用空格。感谢评论中的@CoffeeTableEspresso和@zebralamy)
    (在macOS上,只要您位于降价单元格上,您就可以这样做:![title](../image 1.png),而不必担心空白)。

对于网络图像:

![Image of Yaktocat](https://octodex.github.com/images/yaktocat.png)

如@cristianmtr所示。请注意不要同时使用这些引号""''网址中的引号。

或本地的:

![title](img/picture.png)

由@Sebastian演示

There are several ways to post an image in Jupyter notebooks:

via HTML:

from IPython.display import Image
from IPython.core.display import HTML 
Image(url= "http://my_site.com/my_picture.jpg")

You retain the ability to use HTML tags to resize, etc…

Image(url= "http://my_site.com/my_picture.jpg", width=100, height=100)

You can also display images stored locally, either via relative or absolute path.

PATH = "/Users/reblochonMasque/Documents/Drawings/"
Image(filename = PATH + "My_picture.jpg", width=100, height=100)

if the image it wider than the display settings: thanks

use unconfined=True to disable max-width confinement of the image

from IPython.core.display import Image, display
display(Image('https://i.ytimg.com/vi/j22DmsZEv30/maxresdefault.jpg', width=1900, unconfined=True))

or via markdown:

  • make sure the cell is a markdown cell, and not a code cell, thanks @游凯超 in the comments)
  • Please note that on some systems, the markdown does not allow white space in the filenames. Thanks to @CoffeeTableEspresso and @zebralamy in the comments)
    (On macos, as long as you are on a markdown cell you would do like this: ![title](../image 1.png), and not worry about the white space).

for a web image:

![Image of Yaktocat](https://octodex.github.com/images/yaktocat.png)

as shown by @cristianmtr Paying attention not to use either these quotes "" or those '' around the url.

or a local one:

![title](img/picture.png)

demonstrated by @Sebastian


回答 2

另外,您可以使用纯HTML <img src>,它允许您更改高度和宽度,并仍由markdown解释器读取:

<img src="subdirectory/MyImage.png" width=60 height=60 />

Alternatively, you can use a plain HTML <img src>, which allows you to change height and width and is still read by the markdown interpreter:

<img src="subdirectory/MyImage.png" width=60 height=60 />

回答 3

我知道这并不完全相关,但是由于当您搜索“ 如何在Jupyter中显示图像 ”时,此答案多次排名第一,因此也请考虑此答案。

您可以使用matplotlib如下显示图像。

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread("your_image.png")
plt.imshow(image)
plt.show()

I know this is not fully relevant, but since this answer is ranked first many a times when you search ‘how to display images in Jupyter‘, please consider this answer as well.

You could use matplotlib to show an image as follows.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread("your_image.png")
plt.imshow(image)
plt.show()

回答 4

我很惊讶这里没有人提到html cell magic选项。来自文档(IPython,但与Jupyter相同)

%% html

Render the cell as a block of HTML

I’m surprised no one here has mentioned the html cell magic option. from the docs (IPython, but same for Jupyter)

%%html

Render the cell as a block of HTML

回答 5

除了使用HTML的其他答案(在Markdown中或使用%%HTML魔术:

如果您需要指定图像高度,则将无法使用:

<img src="image.png" height=50> <-- will not work

这是因为Jupyter中的CSS样式height: auto默认情况下会使用img标签来覆盖HTML高度属性。您需要改写CSS height属性:

<img src="image.png" style="height:50px"> <-- works

In addition to the other answers using HTML (either in Markdown or using the %%HTML magic:

If you need to specify the image height, this will not work:

<img src="image.png" height=50> <-- will not work

That is because the CSS styling in Jupyter uses height: auto per default for the img tags, which overrides the HTML height attribute. You need need to overwrite the CSS height attribute instead:

<img src="image.png" style="height:50px"> <-- works

回答 6

将图像直接插入Jupyter笔记本中。

注意:您应该在计算机上拥有图像的本地副本

您可以将图像插入Jupyter笔记本本身。这样,您无需将图像单独保存在文件夹中。

脚步:

  1. 将单元格转换为markdown

    • 在所选单元格上按M

    • 在菜单栏中,单元格>单元格类型>降价。
      注意:将单元格转换为Markdown非常重要,否则,第2步中的“插入图片”选项将无效)
  2. 现在转到菜单栏,然后​​选择编辑->插入图像。

  3. 从磁盘中选择图像并上传。

  4. Ctrl+ EnterShift+ Enter

这将使图像成为笔记本的一部分,您无需在目录或Github中上传。我觉得这看起来更干净,而且不容易出现URL损坏的问题。

Insert the image directly in the Jupyter notebook.

Note: You should have a local copy of the image on your computer

You can insert the image in the Jupyter notebook itself. This way you don’t need to keep the image separately in the folder.

Steps:

  1. Convert the cell to markdown by:

    • pressing M on the selected cell
      OR
    • From menu bar, Cell > Cell Type > Markdown.
      (Note: It’s important to convert the cell to Markdown, otherwise the “Insert Image” option in Step 2 will not be active)
  2. Now go to menu bar and select Edit -> Insert Image.

  3. Select image from your disk and upload.

  4. Press Ctrl+Enter or Shift+Enter.

This will make the image as part of the notebook and you don’t need to upload in the directory or Github. I feel this looks more clean and not prone to broken URL issue.


回答 7

使用Markdown的方法如下:

![Image of Yaktocat](https://octodex.github.com/images/yaktocat.png)

Here’s how you can do it with Markdown:

![Image of Yaktocat](https://octodex.github.com/images/yaktocat.png)

回答 8

  1. 将单元格模式设置为降价
  2. 将图像拖放到单元格中。将创建以下命令:

![image.png](attachment:image.png)

  1. 执行/运行单元格,图像出现。

该图像实际上是嵌入在ipynb笔记本中的,您无需弄乱单独的文件。不幸的是,这还不适用于Jupyter-Lab(v 1.1.4)。

编辑:在JupyterLab版本1.2.6中工作

  1. Set cell mode to Markdown
  2. Drag and drop your image into the cell. The following command will be created:

![image.png](attachment:image.png)

  1. Execute/Run the cell and the image shows up.

The image is actually embedded in the ipynb Notebook and you don’t need to mess around with separate files. This is unfortunately not working with Jupyter-Lab (v 1.1.4) yet.

Edit: Works in JupyterLab Version 1.2.6


回答 9

如果要使用Jupyter Notebook API(现在不再使用IPython),则可以找到ipywidgets Jupyter的子项目。您有一个Image小部件。Docstring指定您有value一个字节参数。因此,您可以执行以下操作:

import requests
from ipywidgets import Image

Image(value=requests.get('https://octodex.github.com/images/yaktocat.png').content)

我同意,使用Markdown样式更简单。但是它向您显示了图像显示Notebook API。您还可以使用widthheight参数调整图像的大小。

If you want to use the Jupyter Notebook API (and not the IPython one anymore), I find the ipywidgets Jupyter’s sub-project. You have an Image widget. Docstring specifies that you have a value parameter which is a bytes. So you can do:

import requests
from ipywidgets import Image

Image(value=requests.get('https://octodex.github.com/images/yaktocat.png').content)

I agree, it’s simpler to use the Markdown style. But it shows you the Image display Notebook API. You can also resize the image with the width and height parameters.


回答 10

这是JupyterPython3的解决方案:

我将图像放在名为的文件夹中ImageTest。我的目录是:

C:\Users\MyPcName\ImageTest\image.png

为了显示图像,我使用了以下表达式:

![title](/notebooks/ImageTest/image.png "ShowMyImage")

还要注意/\

Here is a Solution for Jupyter and Python3:

I droped my images in a folder named ImageTest. My directory is:

C:\Users\MyPcName\ImageTest\image.png

To show the image I used this expression:

![title](/notebooks/ImageTest/image.png "ShowMyImage")

Also watch out for / and \


回答 11

这在降价单元中对我有用。无论如何,如果图像或简单文件,我都无需特别提及。

![](files/picture.png)

This works for me in a markdown cell. Somehow I do not need to mention specifically if its an image or a simple file.

![](files/picture.png)

回答 12

我发现的一件事是,图像的路径必须与笔记本计算机最初加载的位置有关。如果您将CD转到其他目录,例如“图片”,则Markdown路径仍相对于原始加载目录。

One thing I found is the path of your image must be relative to wherever the notebook was originally loaded from. if you cd to a different directory, such as Pictures your Markdown path is still relative to the original loading directory.


回答 13

同意,我遇到了同样的问题,这是可行的,而没有奏效的:

WORKED: <img src="Docs/pinoutDOIT32devkitv1.png" width="800"/>
*DOES NOT WORK: <img src="/Docs/pinoutDOIT32devkitv1.png" width="800"/>
DOES NOT WORK: <img src="./Docs/pinoutDOIT32devkitv1.png" width="800"/>*

Agreed, i had the same issues and this is what worked and what did not:

WORKED: <img src="Docs/pinoutDOIT32devkitv1.png" width="800"/>
*DOES NOT WORK: <img src="/Docs/pinoutDOIT32devkitv1.png" width="800"/>
DOES NOT WORK: <img src="./Docs/pinoutDOIT32devkitv1.png" width="800"/>*

回答 14

尽管上面的许多答案都提供了使用文件或Python代码嵌入图像的方法,但是有一种方法可以仅使用markdown和base64将图像嵌入jupyter笔记本本身!

要在浏览器中查看图像,您可以访问data:image/png;base64,**image data here**以base64编码的PNG图像或data:image/jpg;base64,**image data here**以base64编码的JPG图像的链接。在此答案的末尾可以找到一个示例链接。

要将其嵌入到markdown页面中,只需使用与文件Answers类似的结构,但要使用base64链接:![**description**](data:image/**type**;base64,**base64 data**)。现在,您的图像已100%嵌入到Jupyter Notebook文件中!

示例链接: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==

降价示例: ![smile](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==)

While a lot of the above answers give ways to embed an image using a file or with Python code, there is a way to embed an image in the jupyter notebook itself using only markdown and base64!

To view an image in the browser, you can visit the link data:image/png;base64,**image data here** for a base64-encoded PNG image, or data:image/jpg;base64,**image data here** for a base64-encoded JPG image. An example link can be found at the end of this answer.

To embed this into a markdown page, simply use a similar construct as the file answers, but with a base64 link instead: ![**description**](data:image/**type**;base64,**base64 data**). Now your image is 100% embedded into your Jupyter Notebook file!

Example link: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==

Example markdown: ![smile](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==)


如何在浏览器中增加Jupyter / ipython笔记本的单元格宽度?

问题:如何在浏览器中增加Jupyter / ipython笔记本的单元格宽度?

我想在浏览器中增加ipython笔记本的宽度。我有一个高分辨率的屏幕,我想扩展单元格的宽度/大小以利用这个额外的空间。

谢谢!


编辑:5/2017

我现在使用jupyterthemes:https : //github.com/dunovank/jupyter-themes

和此命令:

jt -t oceans16 -f roboto -fs 12 -cellw 100%

可以将宽度设置为100%,并且主题很好。

I would like to increase the width of the ipython notebook in my browser. I have a high-resolution screen, and I would like to expand the cell width/size to make use of this extra space.

Thanks!


edit: 5/2017

I now use jupyterthemes: https://github.com/dunovank/jupyter-themes

and this command:

jt -t oceans16 -f roboto -fs 12 -cellw 100%

which sets the width to 100% with a nice theme.


回答 0

如果您不想更改默认设置,而只想更改正在使用的当前笔记本的宽度,则可以在单元格中输入以下内容:

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))

If you don’t want to change your default settings, and you only want to change the width of the current notebook you’re working on, you can enter the following into a cell:

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))

回答 1

div.cell解决方案实际上不适用于我的IPython,但是幸运的是有人提出了适用于新IPython的可行解决方案:

创建包含内容的文件~/.ipython/profile_default/static/custom/custom.css(iPython)或~/.jupyter/custom/custom.css(Jupyter)

.container { width:100% !important; }

然后重新启动iPython / Jupyter笔记本。请注意,这将影响所有笔记本电脑。

That div.cell solution didn’t actually work on my IPython, however luckily someone suggested a working solution for new IPythons:

Create a file ~/.ipython/profile_default/static/custom/custom.css (iPython) or ~/.jupyter/custom/custom.css (Jupyter) with content

.container { width:100% !important; }

Then restart iPython/Jupyter notebooks. Note that this will affect all notebooks.


回答 2

为了使它与jupyter(版本4.0.6)一起使用,我创建了以下内容~/.jupyter/custom/custom.css

/* Make the notebook cells take almost all available width */
.container {
    width: 99% !important;
}   

/* Prevent the edit cell highlight box from getting clipped;
 * important so that it also works when cell is in edit mode*/
div.cell.selected {
    border-left-width: 1px !important;
}

To get this to work with jupyter (version 4.0.6) I created ~/.jupyter/custom/custom.css containing:

/* Make the notebook cells take almost all available width */
.container {
    width: 99% !important;
}   

/* Prevent the edit cell highlight box from getting clipped;
 * important so that it also works when cell is in edit mode*/
div.cell.selected {
    border-left-width: 1px !important;
}

回答 3

是时候使用jupyterlab

最后,笔记本电脑急需升级。默认情况下,它使用窗口的整个宽度,就像其他任何成熟的本机IDE一样。

您要做的就是:

pip install jupyterlab
# if you use conda
conda install -c conda-forge jupyterlab
# to run 
jupyter lab    # instead of jupyter notebook

这是blog.Jupyter.org的屏幕截图

It’s time to use jupyterlab

Finally, a much-needed upgrade has come to notebooks. By default, it uses the full width of your window like any other full-fledged native IDE.

All you have to do is:

pip install jupyterlab
# if you use conda
conda install -c conda-forge jupyterlab
# to run 
jupyter lab    # instead of jupyter notebook

Here is a screenshot from blog.Jupyter.org


回答 4

全新安装后,我通常要做的是修改存储所有视觉样式的主css文件。我使用Miniconda,但位置与其他人相似C:\Miniconda3\Lib\site-packages\notebook\static\style\style.min.css

在某些屏幕上,这些分辨率是不同的,并且大于1。为安全起见,我将所有分辨率更改为98%,因此,如果从笔记本电脑上的外接屏幕断开连接,则屏幕宽度仍为98%。

然后,将1140px替换为屏幕宽度的98%

@media (min-width: 1200px) {
  .container {
    width: 1140px;
  }
}

编辑后

@media (min-width: 1200px) {
  .container {
    width: 98%;
  }
}

保存并重新启动笔记本


更新资料

最近不得不在已安装的环境中扩展Jupyter单元,这导致我回到这里提醒自己。

如果您需要在虚拟环境中进行安装,请先安装jupyter。您可以在此子目录中找到css文件

env/lib/python3.6/site-packages/notebook/static/style/stye.min.css

What I do usually after new installation is to modify the main css file where all visual styles are stored. I use Miniconda but location is similar with others C:\Miniconda3\Lib\site-packages\notebook\static\style\style.min.css

With some screens these resolutions are different and more than 1. To be on the safe side I change all to 98% so if I disconnect from my external screens on my laptop I still have 98% screen width.

Then just replace 1140px with 98% of the screen width.

@media (min-width: 1200px) {
  .container {
    width: 1140px;
  }
}

After editing

@media (min-width: 1200px) {
  .container {
    width: 98%;
  }
}

Save and restart your notebook


Update

Recently had to wider Jupyter cells on an environment it is installed, which led me to come back here and remind myself.

If you need to do it in virtual env you installed jupyter on. You can find the css file in this subdir

env/lib/python3.6/site-packages/notebook/static/style/stye.min.css

回答 5

您可以通过从任何单元格调用样式表来设置笔记本的CSS。作为示例,请看Navier Stokes类12个步骤

特别是,创建一个包含

<style>
    div.cell{
        width:100%;
        margin-left:1%;
        margin-right:auto;
    }
</style>

应该给你一个起点。但是,可能有必要也进行调整,例如div.text_cell_render处理降价和代码单元。

如果是该文件,custom.css则添加包含以下内容的单元格:

from IPython.core.display import HTML
def css_styling():
    styles = open("custom.css", "r").read()
    return HTML(styles)
css_styling()

这将应用所有样式,尤其是更改像元宽度。

You can set the CSS of a notebook by calling a stylesheet from any cell. As an example, take a look at the 12 Steps to Navier Stokes course.

In particular, creating a file containing

<style>
    div.cell{
        width:100%;
        margin-left:1%;
        margin-right:auto;
    }
</style>

should give you a starting point. However, it may be necessary to also adjust e.g div.text_cell_render to deal with markdown as well as code cells.

If that file is custom.css then add a cell containing:

from IPython.core.display import HTML
def css_styling():
    styles = open("custom.css", "r").read()
    return HTML(styles)
css_styling()

This will apply all the stylings, and, in particular, change the cell width.


回答 6

(从2018年开始,我建议您尝试使用JupyterHub / JupyterLab。它使用监视器的整个宽度。如果这不是一种选择,则可能是因为您使用的是基于云的Jupyter即服务提供商,继续阅读)

(时尚被指控窃取用户数据,我已改为使用Stylus插件)

我建议使用时尚浏览器插件。这样,您可以覆盖所有笔记本的css,而无需向笔记本中添加任何代码。我们不喜欢在.ipython / profile_default中更改配置,因为我们正在为整个团队运行共享的Jupyter服务器,并且宽度是用户首选项。

我专门为垂直方向的高分辨率屏幕设计了一种样式,该样式使单元格变宽,并在底部添加了一些空白区域,因此您可以将最后一个单元格放置在屏幕的中央。 https://userstyles.org/styles/131230/jupyter-wide 当然,如果您使用其他布局,或者您不希望最后有多余的空格,则可以根据自己的喜好修改我的CSS。

最后但并非最不重要的一点是,Stylish是包含在工具集中的出色工具,因为您可以根据自己的喜好轻松自定义其他站点/工具(例如Jira,Podio,Slack等)。

@media (min-width: 1140px) {
  .container {
    width: 1130px;
  }
}

.end_space {
  height: 800px;
}

(As of 2018, I would advise trying out JupyterHub/JupyterLab. It uses the full width of the monitor. If this is not an option, maybe since you are using one of the cloud-based Jupyter-as-a-service providers, keep reading)

(Stylish is accused of stealing user data, I have moved on to using Stylus plugin instead)

I recommend using Stylish Browser Plugin. This way you can override css for all notebooks, without adding any code to notebooks. We don’t like to change configuration in .ipython/profile_default, since we are running a shared Jupyter server for the whole team and width is a user preference.

I made a style specifically for vertically-oriented high-res screens, that makes cells wider and adds a bit of empty-space in the bottom, so you can position the last cell in the centre of the screen. https://userstyles.org/styles/131230/jupyter-wide You can, of course, modify my css to your liking, if you have a different layout, or you don’t want extra empty-space in the end.

Last but not least, Stylish is a great tool to have in your toolset, since you can easily customise other sites/tools to your liking (e.g. Jira, Podio, Slack, etc.)

@media (min-width: 1140px) {
  .container {
    width: 1130px;
  }
}

.end_space {
  height: 800px;
}

回答 7

对于Chrome用户,我建议使用Stylebot,它可以让您覆盖任何页面上的所有CSS,还可以搜索和安装其他共享自定义CSS。但是,出于我们的目的,我们不需要任何高级主题。打开Stylebot,更改为Edit CSS。Jupyter捕获了一些击键,因此您将无法在其中键入以下代码。只需复制和粘贴,或者仅编辑即可:

#notebook-container.container {
    width: 90%;
}

根据需要更改宽度,我发现90%的外观比100%的外观好。但这完全取决于您。

For Chrome users, I recommend Stylebot, which will let you override any CSS on any page, also let you search and install other share custom CSS. However, for our purpose we don’t need any advance theme. Open Stylebot, change to Edit CSS. Jupyter captures some keystrokes, so you will not be able to type the code below in. Just copy and paste, or just your editor:

#notebook-container.container {
    width: 90%;
}

Change the width as you like, I find 90% looks nicer than 100%. But it is totally up to your eye.


回答 8

这是我最终使用的代码。它将输入和输出单元格向左和向右拉伸。请注意,输入/输出编号指示将消失:

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
display(HTML("<style>.output_result { max-width:100% !important; }</style>"))
display(HTML("<style>.prompt { display:none !important; }</style>"))

This is the code I ended up using. It stretches input & output cells to the left and right. Note that the input/output number indication will be gone:

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
display(HTML("<style>.output_result { max-width:100% !important; }</style>"))
display(HTML("<style>.prompt { display:none !important; }</style>"))

回答 9

我对@ jvd10的解决方案进行了一些修改。“!important”似乎太强了,以至于显示TOC侧栏时容器不能很好地适应。我将其删除并添加了“最小宽度”以限制最小宽度。

这是我的.juyputer / custom / custom.css:

/* Make the notebook cells take almost all available width and limit minimal width to 1110px */
.container {
    width: 99%;
    min-width: 1110px;
}   

/* Prevent the edit cell highlight box from getting clipped;
 * important so that it also works when cell is in edit mode*/
div.cell.selected {
    border-left-width: 1px;
}

I made some modification to @jvd10’s solution. The ‘!important’ seems too strong that the container doesn’t adapt well when TOC sidebar is displayed. I removed it and added ‘min-width’ to limit the minimal width.

Here is my .juyputer/custom/custom.css:

/* Make the notebook cells take almost all available width and limit minimal width to 1110px */
.container {
    width: 99%;
    min-width: 1110px;
}   

/* Prevent the edit cell highlight box from getting clipped;
 * important so that it also works when cell is in edit mode*/
div.cell.selected {
    border-left-width: 1px;
}

回答 10

我尝试了一切,但对我没有用,最终我将数据框显示为HTML,如下所示

from IPython.display import HTML    
HTML (pd.to_html())

I tried everything and nothing worked for me, I ended up using displaying my data frame as HTML as follows

from IPython.display import HTML    
HTML (pd.to_html())

回答 11

对于Firefox / Chrome用户,一种实现100%宽度的好方法是使用自定义TamperMonkey脚本。

好处是

  1. 在浏览器中配置一次,无需修改服务器配置。
  2. 与多个jupyter服务器一起使用。
  3. TamperMonkey受信任,维护且稳定。
  4. 通过javascript可以进行许多其他自定义。

该脚本对我有用https://gist.githubusercontent.com/mrk-andreev/2a9c2538fad0b687c27e192d5948834f/raw/6aa1148573dc20a22fca126e56e3b03f4abf281b/jpn_tmonkey.js

For Firefox/Chrome users, a nice way to achieve 100% width is to use a custom TamperMonkey script.

The benefits are

  1. configure this once in your browser, no need to modify the server configuration.
  2. works with multiple jupyter servers.
  3. TamperMonkey is trusted, maintained, and stable.
  4. Lots of additional customization is possible via javascript.

This script works for me https://gist.githubusercontent.com/mrk-andreev/2a9c2538fad0b687c27e192d5948834f/raw/6aa1148573dc20a22fca126e56e3b03f4abf281b/jpn_tmonkey.js


Pandas-profiling 从Pandas DataFrame对象创建HTML分析报告

Documentation|Slack|Stack Overflow

从熊猫生成配置文件报告DataFrame

熊猫们df.describe()函数很棒,但对于严肃的探索性数据分析来说有点基础pandas_profiling将熊猫DataFrame扩展为df.profile_report()用于快速数据分析

对于每个列,以下统计信息(如果与列类型相关)显示在交互式HTML报告中:

  • 类型推理:检测types数据帧中的列数
  • 要领:类型、唯一值、缺少值
  • 分位数统计如最小值、Q1、中位数、Q3、最大值、范围、四分位数间范围
  • 描述性统计如均值、模态、标准差、和、中位数绝对偏差、变异系数、峰度、偏度
  • 最频繁值
  • 直方图
  • 相关性突出高度相关的变量、Spearman、Pearson和Kendall矩阵
  • 缺少值缺失值的矩阵、计数、热图和树状图
  • 文本分析了解文本数据的类别(大写、空格)、脚本(拉丁文、西里尔文)和块(ASCII
  • 文件和图像分析提取文件大小、创建日期和维度,并扫描截断的图像或包含EXIF信息的图像

公告

发布版本v3.0.0其中对报告配置进行了全面检查,提供了更直观的API并修复了以前全局配置固有的问题

这是第一个坚持SemverConventional Commits规格说明

电光后端正在进行中:我们可以很高兴地宣布,用于生成个人资料报告的电光后端已经接近v1。招聘测试者!电光后端将作为此软件包的预发行版发布

支持pandas-profiling

关于……的发展pandas-profiling完全依赖于捐款。如果您在该包中发现了价值,我们欢迎您通过以下方式直接支持该项目GitHub Sponsors好了!请帮助我继续支持这个方案。特别令人兴奋的是GitHub与您的贡献相匹配第一年

请在此处查找更多信息:

2021年5月9日💘


内容:Examples|Installation|Documentation|Large datasets|Command line usage|Advanced usage|integrations|Support|Types|How to contribute|Editor Integration|Dependencies


示例

下面的示例可以让您对软件包的功能有一个印象:

具体功能:

教程:

安装

使用管道



通过运行以下命令,可以使用pip包管理器进行安装

pip install pandas-profiling[notebook]

或者,您也可以直接从Github安装最新版本:

pip install https://github.com/pandas-profiling/pandas-profiling/archive/master.zip

使用CONDA


通过运行以下命令,可以使用Conda包管理器进行安装

conda install -c conda-forge pandas-profiling

从源开始

通过克隆存储库或按键下载源代码‘Download ZIP’在这一页上

通过导航到正确的目录并运行以下命令来安装:

python setup.py install

文档

的文档pandas_profiling可以找到here以前的文档仍然可用here

快速入门

首先加载您的熊猫DataFrame,例如使用:

import numpy as np
import pandas as pd
from pandas_profiling import ProfileReport

df = pd.DataFrame(np.random.rand(100, 5), columns=["a", "b", "c", "d", "e"])

要生成报告,请运行以下命令:

profile = ProfileReport(df, title="Pandas Profiling Report")

更深入地探索

您可以按您喜欢的任何方式配置配置文件报告。下面的示例代码将explorative configuration file,它包括文本(长度分布、Unicode信息)、文件(文件大小、创建时间)和图像(尺寸、EXIF信息)的许多功能。如果您对使用的确切设置感兴趣,可以与default configuration file

profile = ProfileReport(df, title="Pandas Profiling Report", explorative=True)

了解有关配置的详细信息pandas-profilingAdvanced usage页面

木星笔记本

我们建议使用Jupyter笔记本以交互方式生成报告。有两个界面(参见下面的动画):通过小部件和通过HTML报告

这是通过简单地显示报告来实现的。在Jupyter笔记本中,运行:

profile.to_widgets()

HTML报告可以包含在Jupyter笔记本中:

运行以下代码:

profile.to_notebook_iframe()

保存报告

如果要生成HTML报告文件,请保存ProfileReport添加到对象,并使用to_file()功能:

profile.to_file("your_report.html")

或者,您也可以以JSON的形式获取数据:

# As a string
json_data = profile.to_json()

# As a file
profile.to_file("your_report.json")

大型数据集

版本2.4引入了最小模式

这是禁用代价高昂的计算(如关联和重复行检测)的默认配置

使用以下语法:

profile = ProfileReport(large_dataset, minimal=True)
profile.to_file("output.html")

有基准可用here

命令行用法

对于熊猫可以立即读取的标准格式的CSV文件,您可以使用pandas_profiling可执行文件

有关选项和参数的信息,请运行以下命令

pandas_profiling -h

高级用法

可以使用一组选项来调整生成的报告

  • title(str):报告标题(默认为‘Pandas Profiling Report’)
  • pool_size(int):线程池中的工作进程数。设置为零时,它将设置为可用CPU数(默认情况下为0)
  • progress_bar(bool):如果为True,pandas-profiling将显示进度条
  • infer_dtypes(bool):何时True(默认)dtype的变量是使用visions使用排版逻辑(例如,将整数存储为字符串的列将被视为数字进行分析)

有关更多设置,请参阅default configuration fileminimal configuration file

您可以在高级用法页面上找到配置文档here

示例

profile = df.profile_report(
    title="Pandas Profiling Report", plot={"histogram": {"bins": 8}}
)
profile.to_file("output.html")

集成

寄予厚望

分析数据与数据验证密切相关:通常,验证规则是根据众所周知的统计数据定义的。为此,pandas-profilingGreat Expectations这是一个世界级的开源库,可以帮助您维护数据质量并改善团队之间关于数据的沟通。远大期望允许您创建期望(基本上是数据的单元测试)和数据文档(便于共享的HTML数据报告)pandas-profiling提供了一种基于ProfileReport的结果创建一套预期的方法,您可以存储这些预期,并使用它来验证另一个(或将来的)数据集

您可以找到有关《远大前程》集成的更多详细信息here

支持开源

如果没有我们慷慨的赞助商的支持,维护和开发熊猫侧写的开源代码是不可能的,它有数百万的下载量和数千的用户

Lambda workstations、服务器、笔记本电脑和云服务为财富500强公司和94%的前50所大学的工程师和研究人员提供动力。Lambda Cloud提供4个和8个GPU实例,起步价为1.5美元/小时。预装TensorFlow、PyTorch、Ubuntu、CUDA和cuDNN

我们要感谢我们慷慨的Github赞助商和支持者,是他们让熊猫侧写成为可能:

Martin Sotir, Brian Lee, Stephanie Rivera, abdulAziz, gramster

如果您想出现在此处,请查看更多信息:Github Sponsor page

类型

类型是有效数据分析的强大抽象,它超越了逻辑数据类型(整型、浮点型等)。pandas-profiling目前,可识别以下类型:布尔值、数值、日期、分类、URL、路径、文件图像

我们为Python开发了一个类型系统,为数据分析量身定做:visions选择合适的排版既可以提高整体表现力,又可以降低分析/代码的复杂性。要了解更多信息,请执行以下操作pandas-profiling的类型系统,请签出默认实现here同时,现在完全支持用户自定义摘要和类型定义-如果您有特定的用例,请提出想法或公关!

贡献

请阅读有关参与Contribution Guide

提出问题或开始贡献的一个低门槛的地方是通过接触熊猫-侧写松弛。Join the Slack community

编辑器集成

PyCharm集成

  1. 安装pandas-profiling通过上述说明
  2. 找到您的pandas-profiling可执行文件
    • 在MacOS/Linux/BSD上:
      $ which pandas_profiling
      (example) /usr/local/bin/pandas_profiling
    • 在Windows上:
      $ where pandas_profiling
      (example) C:\ProgramData\Anaconda3\Scripts\pandas_profiling.exe
  3. 在PyCharm中,转到设置(或首选项在MacOS上)>工具>外部工具
  4. 单击+图标以添加新的外部工具
  5. 插入以下值
    • 名称:熊猫侧写
    • 计划:在步骤2中获得的位置
    • 参数:"$FilePath$" "$FileDir$/$FileNameWithoutAllExtensions$_report.html"
    • 工作目录:$ProjectFileDir$

要使用PyCharm集成,请右键单击任意数据集文件:

外部工具>熊猫侧写

其他集成

其他编辑器集成可以通过拉请求进行贡献

依赖项

配置文件报告是用HTML和CSS编写的,这意味着pandas-profiling需要现代浏览器

你需要Python 3来运行此程序包。其他依赖关系可以在需求文件中找到:

文件名 要求
requirements.txt 套餐要求
requirements-dev.txt 发展的要求
requirements-test.txt 测试的规定
setup.py 对微件等的要求

Dash Python、R、Julia和Jupyter的分析型Web应用程序

DASH是用于构建ML和数据科学Web应用程序的下载最多、最值得信赖的Python框架

Dash构建在Plotly.js、Reaction和Flask之上,它将现代UI元素(如下拉列表、滑块和图形)直接绑定到您的分析Python代码。阅读我们自豪地制作的教程❤️由破折号本身

应用程序示例

应用程序 描述
这里有一个简单的Dash App示例,它将下拉菜单绑定到D3.js Ploly Graph。当用户在下拉列表中选择一个值时,应用程序代码会动态地将数据从Google Finance导出到Pandas DataFrame。这个应用程序是刚刚编写的43代码行(view the source)
DASH应用程序代码是声明性和反应性的,这使得构建包含许多交互元素的复杂应用程序变得很容易。下面是一个具有5个输入、3个输出和交叉滤波的示例。此应用程序仅由160行代码组成,所有代码均为Python
破折号使用Plotly.js用来绘制图表。支持超过35种图表类型,包括地图
DASH不仅仅适用于仪表盘。您可以完全控制应用程序的外观。这是一个样式设置为PDF报表的Dash应用程序

要了解有关Dash的更多信息,请阅读extensive announcement letterjump in with the user guide

DASH OSS和DASH Enterprise

使用Dash Open Source,Dash应用程序可在本地笔记本电脑或工作站上运行,但组织中的其他人无法轻松访问

当您的Dash应用程序准备好在部门或公司范围内使用时,使用Dash Enterprise进行纵向扩展。或者,从一开始就使用Dash Enterprise启动您的计划,从Ploly的团队中获得开发人员工作效率的提升和实践加速

ML Ops功能:为ML Ops提供一站式服务:为您的Dash应用程序提供水平可扩展的托管、部署和身份验证。不需要IT或DevOps

  • App manager无需IT或DevOps团队即可部署和管理Dash应用程序。应用程序管理器为您提供对Dash部署的所有方面的点击式控制
  • Kubernetes scaling确保Dash应用程序的高可用性,并利用Dash Enterprise的Kubernetes架构进行横向扩展。不需要IT或掌舵
  • No code auth只需点击几下即可控制Dash应用程序访问。Dash Enterprise支持LDAP、AD、PKI、OKTA、SAML、OpenID Connect、OAuth、SSO和简单的电子邮件身份验证
  • Job Queue作业队列是构建可伸缩的Dash应用程序的关键。将繁重的计算从同步Dash回调移动到作业队列以进行异步后台处理

低码特性:低码Dash应用程序功能,极大地提高了开发人员的工作效率

  • Design Kit像专业人士一样设计,不需要编写一行CSS。轻松安排、设置样式、打造品牌和自定义Dash应用程序
  • Snapshot Engine将Dash应用程序视图保存并共享为链接或PDF。或者,通过Dash运行Python作业,并在作业完成后让快照引擎通过电子邮件发送报告
  • Dashboard ToolkitDash应用程序的拖放布局、图表编辑和交叉过滤器
  • Embedding在不使用IFrame的情况下,在现有Web应用程序或网站中本地嵌入Dash应用程序

企业人工智能功能:您的数据科学团队快速交付AI/ML研究和业务计划所需的一切

  • AI App MarketplaceDash Enterprise附带了数十个Dash应用程序模板,用于解决AI/ML影响最大的业务问题
  • Big Data for Pything连接到Python最流行的大数据后端:Dask、Databricks、NVIDIA Rapids、Snowflake、Postgres、Vaex等
  • GPU & Dask AccelerationDash Enterprise将适用于GPU和并行CPU计算的最流行的Python HPC堆栈交到了企业用户手中
  • Data Science Workspaces从第一天开始高效工作。从Dash Enterprise的板载代码编辑器编写并执行Python、R和Julia代码

看见https://plotly.com/contact-us/为了取得联系

IPython 官方存储库 包含网站、文档构建等内容

IPython:高效交互计算

概述

欢迎来到IPython。有关我们的完整文档,请访问ipython.readthedocs.io并包含有关如何安装、使用和参与项目的信息。IPython(交互式Python)是用于多种编程语言交互计算的命令shell,最初是为Python编程语言开发的,它提供自检、富媒体、shell语法、制表符完成和历史记录

IPython版本和Python支持

从IPython 7.10开始,IPython紧随其后NEP 29

IPython 7.17+需要Python版本3.7及更高版本

IPython 7.10+需要Python 3.6版和更高版本

IPython 7.0需要Python 3.5版和更高版本

IPython 6.x需要Python 3.3版和更高版本

IPython 5.x LTS是与Python2.7兼容的版本。如果您需要Python 2支持,您可以必须使用IPython 5.x LTS。请根据需要更新您的项目配置和要求

笔记本、Qt控制台和许多其他部件现在是朱庇特请参阅Jupyter installation docs如果你想用这些

IPython的主要功能

全面的对象自省

输入历史记录,跨会话持久

在具有自动生成的引用的会话期间缓存输出结果

可扩展的制表符完成,默认情况下支持完成python变量和关键字、文件名和函数关键字

可扩展的“魔术”命令系统,用于控制环境并执行许多与IPython或操作系统相关的任务

丰富的配置系统,可在不同设置之间轻松切换(比每次更改$PYTHONSTARTUP环境变量更简单)

会话记录和重载

用于特殊目的情况的可扩展语法处理

访问具有用户可扩展别名system的系统外壳

可轻松嵌入到其他Python程序和GUI中

对PDB调试器和Python探查器的集成访问

开发与即时运行

您可以在上找到最新版本的开发文档readthedocs

通过在终端键入以下命令,甚至无需在系统范围内安装IPython,即可从该目录运行IPython:

$ python -m IPython

或查看development installation docs有关最新版本的信息,请阅读文档

旧版本IPython的文档和安装说明可在IPython website

IPython需要Python版本3或更高版本

从版本6.0开始,IPython不支持Python 2.7、3.0、3.1或3.2

要获得与Python 2.7兼容的版本,请安装5.x LTS长期支持版本

如果您遇到此错误消息,您可能正在尝试从源代码安装或使用IPython。您需要检查远程5.x分支机构。如果您使用的是GIT,则应该可以执行以下操作:

$ git fetch origin
$ git checkout 5.x

如果您在常规安装IPython时遇到此错误消息,则可能需要更新包管理器,例如,如果您使用的是pip,请使用以下命令检查pip的版本:

$ pip --version

您需要将pip更新到9.0.1版或更高版本。如果您使用的不是pip,请向软件包的维护人员咨询您的软件包管理器。

有关更多信息,请参阅我们的博客帖子之一:

https://blog.jupyter.org/release-of-ipython-5-0-8ce60b8d2e8e

以及以下拉式请求以供讨论:

https://github.com/ipython/ipython/pull/9900

如果您正在调用setup.py直接-这是您不应该使用的-使用或正在使用easy_install如果是这种情况,请使用pip
install .
而不是setup.py install,以及pip install -e .而不是setup.py develop如果您依赖IPython作为依赖项,则可能还希望对IPython具有条件依赖项,具体取决于Python版本:

install_req = ['ipython']
if sys.version_info[0] < 3 and 'bdist_wheel' not in sys.argv:
    install_req.remove('ipython')
    install_req.append('ipython<6')

setup(
    ...
    install_requires=install_req
)

IPython的替代方案

IPython可能不合您的口味;如果是这样,您可能想要使用类似的项目:

忽略带有git故障的提交。忽略reRevsFile

从GIT 2.23开始,可以在不中断的情况下进行格式更改git blame请参阅git documentation有关更多详细信息,请参阅

要使用此功能,您必须:

  • 安装Git>=2.23
  • 通过运行以下命令配置您的本地GIT存储库:
    • POSIX:tools\configure-git-blame-ignore-revs.sh
    • 窗口:tools\configure-git-blame-ignore-revs.bat

Python Bokeh 浏览器中的交互式数据可视化




Bokeh是一个用于现代Web浏览器的交互式可视化程序库。它提供优雅、简洁的多功能图形构造,并在大型或流式数据集上提供高性能的交互性。Bokeh可以帮助任何想要快速、轻松地制作交互式绘图、仪表板和数据应用程序的人

最新版本
孔达

许可证

PyPI

赞助

实时教程

生成状态 静电分析
支持

推特

如果你喜欢伯克并愿意支持我们的使命,请考虑making a donation











































安装

安装Bokeh的最简单方法是使用Anaconda Python distribution及其包含的孔达包裹管理系统。要安装Bokeh及其所需的依赖项,请在Bash或Windows命令提示符下输入以下命令:

conda install bokeh

要使用pip进行安装,请在Bash或Windows命令提示符下输入以下命令:

pip install bokeh

有关更多信息,请参阅installation documentation

资源

安装Bokeh后,请查看first steps guides

访问full documentation site要查看User’s Guidelaunch the Bokeh tutorial要在实时Jupyter笔记本中了解Bokeh,请执行以下操作

社区支持可在Project Discourse

如果您想对Bokeh做出贡献,请查看Developer Guiderequest an invitation to the Bokeh Dev Slack workspace

注意:在Bokeh项目的代码库、问题跟踪器和论坛中互动的每个人都应该遵循Code of Conduct

跟我们走吧

关注我们的推特@bokeh

支持

财政支持

Bokeh项目对此表示感谢individual contributions以下组织和公司提供赞助和支持:

















如果您的公司使用Bokeh并能够赞助该项目,请联系info@bokeh.org

Bokeh是NumFOCUS的赞助项目,NumFOCUS是美国的501(C)(3)非营利性慈善机构。NumFOCUS为Bokeh提供财政、法律和行政支持,以帮助确保项目的健康和可持续性。参观numfocus.org了解更多信息

对Bokeh的捐款由NumFOCUS管理。对于美国的捐赠者,您的捐赠在法律规定的范围内是免税的。与任何捐赠一样,您应该就您的具体税务情况咨询您的税务顾问。

实物支持

Bokeh项目还感谢以下公司捐赠的服务:

安全性

若要报告安全漏洞,请使用Tidelift security contactTidelift将协调修复和披露

Homemade-machine-learning 流行机器学习算法示例,并解释了交互式🤖演示和数学

有监督的学习

在有监督的学习中,我们有一组训练数据作为输入,有一组标签或每个训练集的“正确答案”作为输出。然后,我们正在训练我们的模型(机器学习算法参数),以正确地将输入映射到输出(以进行正确的预测)。最终目的是找到能够成功继续正确运行的模型参数输入→输出映射(预测),即使对于新的输入示例也是如此

回归

在回归问题中,我们做实值预测。基本上,我们尝试沿着训练示例绘制一条直线/平面/n维平面

使用示例:股价预测、销售分析、任意数字依赖等

🤖线性回归

分类

在分类问题中,我们按一定的特征划分输入样本

使用示例:垃圾邮件过滤器、语言检测、查找相似文档、手写字母识别等

🤖Logistic回归

无监督学习

无监督学习是机器学习的一个分支,它从没有标记、分类或分类的测试数据中学习。无监督学习不是响应反馈,而是识别数据中的共性,并根据每个新数据中是否存在这些共性来做出反应

群集

在聚类问题中,我们根据未知特征对训练样本进行拆分。算法本身决定使用什么特征进行分割

使用示例:市场细分、社交网络分析、组织计算集群、天文数据分析、图像压缩等

🤖K-均值算法

异常检测

异常检测(也称为离群值检测)是通过与大多数数据显著不同来识别引起怀疑的稀有项目、事件或观测

使用示例:入侵检测、欺诈检测、系统健康监控、从数据集中删除异常数据等

🤖基于高斯分布的异常检测

神经网络(NN)

神经网络本身不是一种算法,而是许多不同的机器学习算法协同工作并处理复杂数据输入的框架

使用示例:作为替身所有其他算法的总称,图像识别、语音识别、图像处理(应用特定风格)、语言翻译等

🤖多层感知器(MLP)

机器学习地图

以下机器学习主题地图的来源是this wonderful blog post

必备条件

安装Python

确保你有Python installed在您的机器上

您可能想要使用venv创建虚拟环境的标准Python库,pip以及从本地项目目录安装和提供的所有从属软件包,以避免扰乱系统范围的软件包及其版本

安装依赖项

通过运行以下命令安装项目所需的所有依赖项:

pip install -r requirements.txt

在当地发射木星

项目中的所有演示都可以直接在您的浏览器中运行,而无需在本地安装Jupyter。但如果你想发射Jupyter Notebook在本地,您可以通过从项目的根文件夹运行以下命令来完成此操作:

jupyter notebook

在此之后,Jupyter笔记本将可以通过以下方式访问http://localhost:8888

远程发射木星

每个算法部分都包含指向以下内容的演示链接Jupyter NBViewer这是Jupyter笔记本的快速在线预览器,您可以在浏览器中直接看到演示代码、图表和数据,而无需在本地安装任何东西。如果你想的话变化代码和实验使用演示笔记本时,您需要在中启动笔记本Binder您只需单击“在活页夹上执行”NBViewer右上角的链接

数据集

可在以下位置找到用于Jupyter笔记本演示的数据集列表data folder

支持该项目

您可以通过以下方式支持此项目❤️️GitHub或❤️️Patreon