一些建议如何设定 Python 对于统计分析

R用户来Python做统计分析的时候都一定知道IPython没有很重要的DataFrame类,也没有其它对于马上开始数据分析方便的函数。所以,希望用Python为了做数据分析的时候,我觉得最麻烦的事之一,是几乎每次要import这些包。那么,我在这里要描写一个很简单的方法如何把所有的重要的工具自动import:

建议

1. 生成IPython文件:

$ ipython profile create

这个命令应该生成config文件,比如:
/home/you/.config/ipython/profile_default/ipython_config.py
/home/you/.config/ipython/profile_default/ipython_qtconsole_config.py
/home/you/.config/ipython/profile_default/ipython_notebook_config.py

2. 下定义你需要什么:

编辑上面生成的所有的文件,里面包括,比如:

c.InteractiveShellApp.exec_lines = [
    'import numpy as np',
    'import pandas as pd',
    'import matplotlib.pyplot as plt',
    'import scipy as sp',
    'import statsmodels.api as sm',
    'from pandas import Series, DataFrame',
    '%load_ext rmagic',
    'import pandas.rpy.common as rpy',
    'pd.set_option("notebook_repr_html", False)',
    'pd.set_option("max_rows",5000)',
    'pd.set_option("max_columns",50)',
    'pd.set_option("display.max_columns", 50)',
    'pd.set_option("display.height", 10000)',
    'pd.set_option("display.width", 10000)',
    'import sympy as sy',
    'from sympy import diff',
    'from sympy import integrate as intt',
    'a, b, c, x, y, z, t = sy.symbols("a b c x y z t")',
    'k, m, n = sy.symbols("k m n", integer=True)',
    'f, g, h = sy.symbols("f g h", cls=sy.Function)',
]
 
c.InteractiveShellApp.exec_files = [ "/home/you/.config/ipython/runatstartup.py" ]

然后编辑 runatstartup.py 文件为了附加多行函数:
def to_r(df, name):
    """Sends variables to R (thanks to Wes McKinney)"""
    from rpy2.robjects import r, globalenv
    r_df = rpy.convert_to_r_dataframe(df)
    globalenv[name] = r_df

(比如,这个 to_r()函数对发出Python的变量到R的时候很方便。

3. 重新开始IPython

下面可以看看之后开始数据分析在Python和R一起多么方便: