一、资源

# code
print "Hello World!"
Hello World!

获取帮助

import numpy as np
??np # 弹出一个帮助窗口
# np. tab 自动补全

二、输入输出及历史

'_' 表示上一次输出,类似matlab里的ans变量

2 + 10
12
_
12

Output history

The output is stored in _N and Out[N] variables:

Out[4]
12
_3
12
print('last output:', _)
print('next one   :', __)
print('and next   :', ___)
('last output:', 12)
('next one   :', 12)
('and next   :', 12)

Input history

The input is stored in _iN and In[N] variables:

In[8]
u'In[8]'
_ii
u"print('last output:', _)\nprint('next one   :', __)\nprint('and next   :', ___)"
_i8
u'In[8]'

三、操作系统

Note: the commands below work on Linux or Macs, but may behave differently on Windows, as the underlying OS is different. IPython's ability to access the OS is still the same, it's just the syntax that varies per OS.

!pwd
/Users/yongle/Data102/note/1w
!ls
fig           ipython.md    markdown.md   test.txt      vim.md
ipython.ipynb linux.md      readme.md     toolbox.md
files = !ls
print("My current directory's files:")
for a_file in files:
    print(a_file)
My current directory's files:
fig
ipython.ipynb
ipython.md
linux.md
markdown.md
readme.md
test.txt
toolbox.md
vim.md

四、Magic Functions

The IPyhton 'magic' functions are a set of commands, invoked by prepending one or two % signs to their name, that live in a namespace separate from your normal Python variables and provide a more command-like interface. They take flags with -- and arguments without quotes, parentheses or commas. The motivation behind this system is two-fold:

  • To provide an orthogonal namespace for controlling IPython itself and exposing other system-oriented functionality.

  • To expose a calling mode that requires minimal verbosity and typing while working interactively. Thus the inspiration taken from the classic Unix shell style for commands.

%timeit range(100) #time inline code
The slowest run took 4.15 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 747 ns per loop
%%timeit #time cell code
range(10)
range(100)
The slowest run took 5.48 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.09 µs per loop

Run bash command

%%bash
echo "My shell is:" $SHELL
echo "User:" $USER
My shell is: /bin/zsh
User: yongle

New file

%%file test.txt
This is a test file!
It can contain anything I want...

more...
Overwriting test.txt
!ls
fig           ipython.md    markdown.md   test.txt      vim.md
ipython.ipynb linux.md      readme.md     toolbox.md
!cat test.txt
This is a test file!
It can contain anything I want...

more...

五、模块小练习

%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf
from matplotlib.pyplot import gcf
/usr/local/lib/python2.7/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')

简单绘图

x = np.linspace(0, 2*np.pi, 300)
y = np.sin(x**2)
plt.plot(x, y)
plt.title("A little chirp")
f = gcf()  # let's keep the figure object around for later...

png

小的线性回归练习

# get x from random data
miu, sigma = 5, 7
x_1 = np.random.normal(miu,sigma,1000)
plt.hist(x_1,bins=100)
plt.show()

png

# set params, I want to compare them with regression values
true_error = np.random.normal(0,2,1000)
true_beta_0 = 1.1
true_beta_1 = -8.2
y = true_beta_0 + true_beta_1*x_1 + true_error
plt.hist(y,bins=100);
plt.show()

png

# simply plot to guess relationship
plt.scatter(x_1,y);

png

df1 = pd.DataFrame(x_1,y)
lm = smf.ols(formula='y ~ x_1', data=df1).fit()
lm.params
Intercept    1.030922
x_1         -8.192709
dtype: float64
系数 真实值 拟合值
intercept 1.1 1.041630
x_1系数 -8.2 -1.041630

六、公式

LaTeX/Mathematics

只要记住基本规则,就很简单了,比如把公式放在dollar符之间,用逃逸符\等。比如\forall x \in X, \, \exists y \leq \epsilon 对应$\forall x \in X, \, \exists y \leq \epsilon$: 把\forall放在两个dollar符之间,表示 $\forall$。dollar符号声明是公式,\表示forall有特殊含义。之后的一个cheatsheet就搞定了。

Greek letters:
  • alpha: $\alpha$
  • beta: $\beta$
  • gamma: $\gamma$
  • pi: $\pi$
  • phi: $\phi$
  • varphi: $\varphi$
  • ...
Operators
  • $\cos(2\theta)$ ---> \cos(2\theta)
  • $\cos^2 \theta$ ---> \cos^2 \theta
  • $\lim_{x \to \infty} \exp(-x) = 0$
  • \lim_{x \to \infty} \exp(-x) = 0
Powers and indices
  • $k{n+1}$ ---> k{n+1} use _ for lowering
  • $k_n^2$ ---> k_n^2 use ^ for raising
  • $n^{22}$ ---> n^{22} use {} for complex situtation
Fractions and Binomials

A fraction is created using the \frac{numerator}{denominator} command.

  • $\frac{n!}{k!(n-k)!}$ ---> \frac{n!}{k!(n-k)!}
  • $\binom{n}{k}$ ---> \binom{n}{k}
Roots

The \sqrt command creates a square root surrounding an expression.

  • $\sqrt{\frac{a}{b}}$ ---> \sqrt{\frac{a}{b}}
  • $\sqrt[n]{1+x+x^2+x^3+\ldots}$ ---> \sqrt[n]{1+x+x^2+x^3+\ldots}
Sums and integrals

The \sum and \int commands insert the sum and integral symbols respectively, with limits specified using the caret (^) and underscore (_).

  • $\sum{i=1}^{10} t_i$ ---> \sum{i=1}^{10} t_i
  • $\int_0^\infty \mathrm{e}^{-x}\, \mathrm{d}x$ ---> \int_0^\infty \mathrm{e}^{-x}\, \mathrm{d}x

results matching ""

    No results matching ""