将 python 帮助中的示例提取到 ipython 会话中

Extract example from python help into ipython session

ipython 我可以 运行 诸如

import pandas as pd
pd.DataFrame.join?

并查看 DataFrame 的帮助。

帮助文件末尾经常有例子,比如

Another option to join using the key columns is to use the `on`
parameter. DataFrame.join always uses `other`'s index but we can use
any column in `df`. This method preserves the original DataFrame's
index in the result.

>>> df.join(other.set_index('key'), on='key')
  key   A    B
0  K0  A0   B0
1  K1  A1   B1
2  K2  A2   B2
3  K3  A3  NaN
4  K4  A4  NaN
5  K5  A5  NaN

我想知道是否有一种快速方法可以将这些示例提取到当前会话中,以便我可以进一步研究它们,或者我是否必须从帮助文件中复制粘贴(然后调整)代码。

对于通用 Python 示例,复制示例然后 粘贴它; IPython 足够聪明,可以理解 Python 的 >>>... 前缀,以及它自己的前缀格式。请参阅 IPython 手册中的 Pasting of code starting with Python or IPython prompts

我正在从此处的文档中复制前两个示例:

In [1]: import pandas as pd

In [2]: pd.DataFrame.join?

In [3]: >>> df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'],
   ...: ...                    'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})

In [4]: df
Out[4]:
  key   A
0  K0  A0
1  K1  A1
2  K2  A2
3  K3  A3
4  K4  A4
5  K5  A5

In [5]: >>> other = pd.DataFrame({'key': ['K0', 'K1', 'K2'],
    ...: ...                       'B': ['B0', 'B1', 'B2']})

您也可以使用 %paste terminal magic command 让 IPython 做同样的事情;此命令直接从剪贴板中提取数据。

这里我把第三个例子放到剪贴板上:

In [6]: %paste
>>> df.set_index('key').join(other.set_index('key'))
## -- End pasted text --
Out[6]:
      A    B
key
K0   A0   B0
K1   A1   B1
K2   A2   B2
K3   A3  NaN
K4   A4  NaN
K5   A5  NaN

还有 %cpaste magic command,提示您将 Python 代码粘贴到其中。您可以多次执行此操作(也许来自不同的部分),直到您在一行中单独输入 -- 双破折号。这确实需要您将示例排列在另一个位置以便从中复制,或者您使用可以让您回忆以前条目的剪贴板。

您也可以仅复制 df 数据帧输出并使用 pandas.read_clipboard() function 让 Pandas 从您的剪贴板读取它;从列行开始复制;这是文档中显示的最终数据帧输出:

In [7]: pd.DataFrame.join?

In [8]: pd.read_clipboard('\s\s+')
Out[8]:
  key   A    B
0  K0  A0   B0
1  K1  A1   B1
2  K2  A2   B2
3  K3  A3  NaN
4  K4  A4  NaN
5  K5  A5  NaN

我用的是\s\s+而不是默认的\s+;它更健壮,因为它可以让您接受其中包含单个 space 的列名。