小编mic*_*ard的帖子

将代码片段复制到 IPython / Jupyter Notebooks

请注意,我的问题是专门针对 Jupyter Notebooks 的。此外,我不只是想运行代码,就像您可以使用%paste. 我想将代码片段粘贴到一个单元格中并在运行前对其进行编辑。(所以这不是这个问题这个问题的重复。)

Pandas 和 seaborn 文档中的许多示例片段的形式如下:

>>> import pandas as pd
>>> df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'},
...                    'B': {0: 1, 1: 3, 2: 5},
...                    'C': {0: 2, 1: 4, 2: 6}})
>>> df
Run Code Online (Sandbox Code Playgroud)

为了摆脱“>>>”和“...”,我目前将代码片段粘贴到 Sublime Text 编辑器中,使用多光标正确格式化代码,然后将其粘贴到笔记本单元格中。

有没有更有效的方法来做到这一点,如果有,它是什么?

python ipython jupyter jupyter-notebook

5
推荐指数
1
解决办法
2229
查看次数

熊猫:构建一个自引用过去值的列

我需要生成一个以初始值开头的列,然后由包含该列的过去值的函数生成.例如

df = pd.DataFrame({'a': [1,1,5,2,7,8,16,16,16]})
df['b'] = 0
df.ix[0, 'b'] = 1
df

    a  b
0   1  1
1   1  0
2   5  0
3   2  0
4   7  0
5   8  0
6  16  0
7  16  0
8  16  0
Run Code Online (Sandbox Code Playgroud)

现在,我想通过获取前一行的最小值并添加两行来生成列'b'的其余部分.一个解决方案是

for i in range(1, len(df)):
    df.ix[i, 'b'] = df.ix[i-1, :].min() + 2
Run Code Online (Sandbox Code Playgroud)

产生了所需的输出

    a   b
0   1   1
1   1   3
2   5   3
3   2   5
4   7   4
5   8   6
6  16   8
7 …
Run Code Online (Sandbox Code Playgroud)

python vectorization pandas

5
推荐指数
1
解决办法
88
查看次数

set.union()抱怨它在传入生成器时没有参数

这是来自Wes Mckinney的Python for Data Analysis的第204页

genre_iter = (set(x.split('|')) for x in movies.genres)
genres = sorted(set.union(*genre_iter))
Run Code Online (Sandbox Code Playgroud)

%paste在IPython中使用该方法时,此代码非常有效.在Python shell中运行时,代码也可以正常运行.但是,当我直接在IPython中键入第二行时,没有%paste方法

genres = sorted(set.union(*genre_iter))
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

TypeError: descriptor 'union' of 'set' object needs an argument
Run Code Online (Sandbox Code Playgroud)

这似乎是一个bug,除非有一个我仍然没有意识到的IPython功能.

python generator ipython

4
推荐指数
1
解决办法
2242
查看次数

Scipy interpolate返回一个'无量纲'数组

我理解interp1d期望插值的数组,但是传递浮点数时的行为很奇怪,可以询问发生了什么以及究竟返回了什么

import numpy as np
from scipy.interpolate import interp1d

x = np.array([1,2,3,4])
y = np.array([5,7,9,15])
f = interp1d(x,y, kind='cubic')
a = f(2.5)

print(repr(a))
print("type is {}".format(type(a)))
print("shape is {}".format(a.shape))
print("ndim is {}".format(a.ndim))
print(a)
Run Code Online (Sandbox Code Playgroud)

输出:

array(7.749999999999992)
type is <class 'numpy.ndarray'>
shape is ()
ndim is 0
7.749999999999992
Run Code Online (Sandbox Code Playgroud)

编辑:为了澄清,我不希望numpy甚至有一个无量纲,无形的数组,更不用一个scipy函数返回一个.

print("Numpy version is {}".format(np.__version__))
print("Scipy version is {}".format(scipy.__version__))

Numpy version is 1.10.4
Scipy version is 0.17.0
Run Code Online (Sandbox Code Playgroud)

python interpolation numpy scipy

3
推荐指数
1
解决办法
1006
查看次数