第三章:IPython交互式開發環境Day5

說明:本文章爲Python數據處理學習日誌,記錄內容爲實現書本內容時遇到的錯誤以及一些與書本不一致的地方,一些簡單操作則不再贅述。日誌主要內容來自書本《利用Python進行數據分析》,Wes McKinney著,機械工業出版社。

1.魔術命令%reset

Docstring:
Resets the namespace by removing all names defined by the user, if
called without arguments, or by removing some types of objects, such
as everything currently in IPython's In[] and Out[] containers (see
the parameters for details).

Parameters
----------
-f : force reset without asking for confirmation.

-s : 'Soft' reset: Only clears your namespace, leaving history intact.
    References to objects may be kept. By default (without this option),
    we do a 'hard' reset, giving you a new session and removing all
    references to objects from the current session.

in : reset input history

out : reset output history

dhist : reset directory history

array : reset only variables that are NumPy arrays

See Also
--------
reset_selective : invoked as ``%reset_selective``

Examples
--------
::

  In [6]: a = 1

  In [7]: a
  Out[7]: 1

  In [8]: 'a' in _ip.user_ns
  Out[8]: True

  In [9]: %reset -f

  In [1]: 'a' in _ip.user_ns
  Out[1]: False

  In [2]: %reset -f in
  Flushing input history

  In [3]: %reset -f dhist in
  Flushing directory history
  Flushing input history

Notes
-----
Calling this magic from clients that do not implement standard input,
such as the ipython notebook interface, will reset the namespace
without confirmation.

按照說明,實現上述的例子,出現錯誤,暫未解決。

a = 2

a
Out[3]: 2

'a' in _ip.user_ns
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-5d0d03f3ce6b> in <module>()
----> 1 'a' in _ip.user_ns

NameError: name '_ip' is not defined 

用dir()函數顯示所有定義過的變量,並沒有_ip,懷疑沒有導入某個包:

print dir()
['ALLOW_THREADS', 'Annotation', 'Arrow', 'Artist', 'AutoLocator', 'Axes', 'BUFSIZE', 'Button', 'CLIP', 'CanopyPdb', 'Circle', 'ComplexWarning', 'DAILY', 'DataSource', 'DateFormatter', 'DateLocator', 'DayLocator', 'ERR_CALL', 'ERR_DEFAULT', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', 'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'FR', 'False_', 'Figure', 'FigureCanvasBase', 'FixedFormatter', 'FixedLocator', 'FormatStrFormatter', 'Formatter', 'FuncFormatter', 'GridSpec', 'HOURLY', 'HourLocator', 'In', 'IndexDateFormatter', 'IndexLocator', 'Inf', 'Infinity', 'LinAlgError', 'Line2D', 'LinearLocator', 'Locator', 'LogFormatter', 'LogFormatterExponent', 'LogFormatterMathtext', 'LogLocator', 'MAXDIMS', 'MINUTELY', 'MO', 'MONTHLY', 'MachAr', 'MaxNLocator', 'MinuteLocator', 'ModuleDeprecationWarning', 'MonthLocator', 'MultipleLocator', 'NAN', 'NINF', 'NZERO', 'NaN', 'Normalize', 'NullFormatter', 'NullLocator', 'Out', 'PINF', 'PZERO', 'PackageLoader', 'PolarAxes', 'Polygon', 'RAISE', 'RRuleLocator', 'RankWarning', 'Rectangle', 'SA', 'SECONDLY', 'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID', 'SHIFT_OVERFLOW', 'SHIFT_UNDERFLOW', 'SU', 'ScalarFormatter', 'ScalarType', 'SecondLocator', 'Slider', 'Subplot', 'SubplotTool', 'TH', 'TU', 'Tester', 'Text', 'TickHelper', 'True_', 'UFUNC_BUFSIZE_DEFAULT', 'UFUNC_PYVALS_NAME', 'VisibleDeprecationWarning', 'WE', 'WEEKLY', 'WRAP', 'WeekdayLocator', 'Widget', 'YEARLY', 'YearLocator', '_', '_3', '_5', '__', '___', '__builtin__', '__builtins__', '__doc__', '__name__', '__package__', '__version__', '_dh', '_i', '_i1', '_i2', '_i3', '_i4', '_i5', '_i6', '_ih', '_ii', '_iii', '_oh', '_sh', 'a', 'absolute', 'absolute_import', 'acorr', 'add', 'add_docstring', 'add_newdoc', 'add_newdoc_ufunc', 'add_newdocs', 'alen', 'all', 'allclose', 'alltrue', 'alterdot', 'amap', 'amax', 'amin', 'angle', 'angle_spectrum', 'annotate', 'any', 'append', 'apply_along_axis', 'apply_over_axes', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argpartition', 'argsort', 'argwhere', 'around', 'array', 'array2string', 'array_equal', 'array_equiv', 'array_repr', 'array_split', 'array_str', 'arrow', 'asanyarray', 'asarray', 'asarray_chkfinite', 'ascontiguousarray', 'asfarray', 'asfortranarray', 'asmatrix', 'asscalar', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'autoscale', 'autumn', 'average', 'axes', 'axhline', 'axhspan', 'axis', 'axvline', 'axvspan', 'bar', 'barbs', 'barh', 'bartlett', 'base_repr', 'bench', 'beta', 'binary_repr', 'bincount', 'binomial', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'bivariate_normal', 'blackman', 'bmat', 'bone', 'bool8', 'bool_', 'box', 'boxplot', 'broadcast', 'broadcast_arrays', 'broadcast_to', 'broken_barh', 'busday_count', 'busday_offset', 'busdaycalendar', 'byte', 'byte_bounds', 'bytes', 'bytes_', 'c_', 'can_cast', 'cast', 'cbook', 'cbrt', 'cdouble', 'ceil', 'center_matrix', 'cfloat', 'char', 'character', 'chararray', 'chisquare', 'choice', 'cholesky', 'choose', 'cla', 'clabel', 'clf', 'clim', 'clip', 'clongdouble', 'clongfloat', 'close', 'cm', 'cohere', 'colorbar', 'colormaps', 'colors', 'column_stack', 'common_type', 'compare_chararrays', 'complex128', 'complex64', 'complex_', 'complexfloating', 'compress', 'concatenate', 'cond', 'conj', 'conjugate', 'connect', 'contour', 'contourf', 'convolve', 'cool', 'copper', 'copy', 'copysign', 'copyto', 'corrcoef', 'correlate', 'cos', 'cosh', 'count_nonzero', 'cov', 'cross', 'csd', 'csingle', 'csv2rec', 'ctypeslib', 'cumprod', 'cumproduct', 'cumsum', 'cycler', 'date2num', 'datestr2num', 'datetime', 'datetime64', 'datetime_as_string', 'datetime_data', 'dedent', 'deg2rad', 'degrees', 'delaxes', 'delete', 'demean', 'deprecate', 'deprecate_with_doc', 'det', 'detrend', 'detrend_linear', 'detrend_mean', 'detrend_none', 'diag', 'diag_indices', 'diag_indices_from', 'diagflat', 'diagonal', 'diff', 'digitize', 'dirichlet', 'disconnect', 'disp', 'display', 'dist', 'dist_point_to_segment', 'distances_along_curve', 'divide', 'division', 'docstring', 'dot', 'double', 'drange', 'draw', 'draw_all', 'draw_if_interactive', 'dsplit', 'dstack', 'dtype', 'e', 'ediff1d', 'eig', 'eigh', 'eigvals', 'eigvalsh', 'einsum', 'emath', 'empty', 'empty_like', 'entropy', 'epoch2num', 'equal', 'errorbar', 'errstate', 'euler_gamma', 'eventplot', 'exception_to_str', 'exit', 'exp', 'exp2', 'exp_safe', 'expand_dims', 'expm1', 'exponential', 'extract', 'eye', 'f', 'fabs', 'fastCopyAndTranspose', 'fft', 'fft2', 'fftfreq', 'fftn', 'fftpack', 'fftpack_lite', 'fftshift', 'fftsurr', 'figaspect', 'figimage', 'figlegend', 'fignum_exists', 'figsize', 'figtext', 'figure', 'fill', 'fill_between', 'fill_betweenx', 'fill_diagonal', 'find', 'find_common_type', 'findobj', 'finfo', 'fix', 'flag', 'flatiter', 'flatnonzero', 'flatten', 'flexible', 'fliplr', 'flipud', 'float16', 'float32', 'float64', 'float_', 'floating', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod', 'format_parser', 'frange', 'frexp', 'frombuffer', 'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromregex', 'fromstring', 'full', 'full_like', 'fv', 'gamma', 'gca', 'gcf', 'gci', 'generic', 'genfromtxt', 'geometric', 'get', 'get_array_wrap', 'get_backend', 'get_cmap', 'get_current_fig_manager', 'get_figlabels', 'get_fignums', 'get_include', 'get_ipython', 'get_plot_commands', 'get_printoptions', 'get_scale_docs', 'get_scale_names', 'get_sparse_matrix', 'get_state', 'get_xyz_where', 'getbuffer', 'getbufsize', 'geterr', 'geterrcall', 'geterrobj', 'getfigs', 'getp', 'ginput', 'gradient', 'gray', 'greater', 'greater_equal', 'grid', 'griddata', 'gumbel', 'half', 'hamming', 'hanning', 'helper', 'hexbin', 'hfft', 'hist', 'hist2d', 'histogram', 'histogram2d', 'histogramdd', 'hlines', 'hold', 'hot', 'hsplit', 'hstack', 'hsv', 'hypergeometric', 'hypot', 'i0', 'identity', 'ifft', 'ifft2', 'ifftn', 'ifftshift', 'ihfft', 'iinfo', 'imag', 'imread', 'imsave', 'imshow', 'in1d', 'index_exp', 'indices', 'inexact', 'inf', 'inferno', 'info', 'infty', 'inner', 'insert', 'inside_poly', 'install_repl_displayhook', 'int0', 'int16', 'int32', 'int64', 'int8', 'int_', 'int_asbuffer', 'intc', 'integer', 'interactive', 'interp', 'intersect1d', 'intp', 'inv', 'invert', 'ioff', 'ion', 'ipmt', 'irfft', 'irfft2', 'irfftn', 'irr', 'is_busday', 'is_closed_polygon', 'is_numlike', 'is_string_like', 'isclose', 'iscomplex', 'iscomplexobj', 'isfinite', 'isfortran', 'ishold', 'isinf', 'isinteractive', 'isnan', 'isneginf', 'isposinf', 'ispower2', 'isreal', 'isrealobj', 'isscalar', 'issctype', 'issubclass_', 'issubdtype', 'issubsctype', 'isvector', 'iterable', 'ix_', 'jet', 'kaiser', 'kron', 'l1norm', 'l2norm', 'lapack_lite', 'laplace', 'ldexp', 'left_shift', 'legend', 'less', 'less_equal', 'lexsort', 'linalg', 'linspace', 'little_endian', 'load', 'load_data', 'loads', 'loadtxt', 'locator_params', 'log', 'log10', 'log1p', 'log2', 'logaddexp', 'logaddexp2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logistic', 'loglog', 'lognormal', 'logseries', 'logspace', 'longcomplex', 'longdouble', 'longest_contiguous_ones', 'longest_ones', 'longfloat', 'longlong', 'lookfor', 'lstsq', 'ma', 'mafromtxt', 'magma', 'magnitude_spectrum', 'margins', 'mask_indices', 'mat', 'math', 'matmul', 'matplotlib', 'matrix', 'matrix_power', 'matrix_rank', 'matshow', 'maximum', 'maximum_sctype', 'may_share_memory', 'mean', 'median', 'memmap', 'meshgrid', 'mgrid', 'min_scalar_type', 'minimum', 'minorticks_off', 'minorticks_on', 'mintypecode', 'mirr', 'mlab', 'mod', 'modf', 'movavg', 'mpl', 'msort', 'multi_dot', 'multinomial', 'multiply', 'multivariate_normal', 'mx2num', 'nan', 'nan_to_num', 'nanargmax', 'nanargmin', 'nanmax', 'nanmean', 'nanmedian', 'nanmin', 'nanpercentile', 'nanprod', 'nanstd', 'nansum', 'nanvar', 'nbytes', 'ndarray', 'ndenumerate', 'ndfromtxt', 'ndim', 'ndindex', 'nditer', 'negative', 'negative_binomial', 'nested_iters', 'new_figure_manager', 'newaxis', 'newbuffer', 'nextafter', 'noncentral_chisquare', 'noncentral_f', 'nonzero', 'norm', 'norm_flat', 'normal', 'normpdf', 'not_equal', 'np', 'nper', 'npv', 'num2date', 'num2epoch', 'number', 'numpy', 'obj2sctype', 'object0', 'object_', 'ogrid', 'ones', 'ones_like', 'outer', 'over', 'packbits', 'pad', 'pareto', 'partition', 'path_length', 'pause', 'pcolor', 'pcolormesh', 'percentile', 'permutation', 'phase_spectrum', 'pi', 'pie', 'piecewise', 'pink', 'pinv', 'pkgload', 'place', 'plasma', 'plot', 'plot_date', 'plotfile', 'plotting', 'plt', 'pmt', 'poisson', 'polar', 'poly', 'poly1d', 'poly_below', 'poly_between', 'polyadd', 'polyder', 'polydiv', 'polyfit', 'polyint', 'polymul', 'polysub', 'polyval', 'power', 'ppmt', 'prctile', 'prctile_rank', 'print_function', 'prism', 'prod', 'product', 'promote_types', 'psd', 'ptp', 'put', 'putmask', 'pv', 'pylab', 'pylab_setup', 'pyplot', 'qr', 'quit', 'quiver', 'quiverkey', 'r_', 'rad2deg', 'radians', 'rand', 'randint', 'randn', 'random', 'random_integers', 'random_sample', 'ranf', 'rank', 'rate', 'ravel', 'ravel_multi_index', 'rayleigh', 'rc', 'rcParams', 'rcParamsDefault', 'rc_context', 'rcdefaults', 'real', 'real_if_close', 'rec', 'rec2csv', 'rec_append_fields', 'rec_drop_fields', 'rec_join', 'recarray', 'recfromcsv', 'recfromtxt', 'reciprocal', 'record', 'register_cmap', 'relativedelta', 'remainder', 'repeat', 'require', 'reshape', 'resize', 'restoredot', 'result_type', 'rfft', 'rfft2', 'rfftfreq', 'rfftn', 'rgrids', 'right_shift', 'rint', 'rk4', 'rms_flat', 'roll', 'rollaxis', 'roots', 'rot90', 'round_', 'row_stack', 'rrule', 's_', 'safe_eval', 'sample', 'save', 'savefig', 'savetxt', 'savez', 'savez_compressed', 'sca', 'scatter', 'sci', 'sctype2char', 'sctypeDict', 'sctypeNA', 'sctypes', 'searchsorted', 'seed', 'segments_intersect', 'select', 'semilogx', 'semilogy', 'set_cmap', 'set_license_directories', 'set_lock_file', 'set_numeric_ops', 'set_printoptions', 'set_state', 'set_string_function', 'setbufsize', 'setdiff1d', 'seterr', 'seterrcall', 'seterrobj', 'setp', 'setxor1d', 'shape', 'short', 'show', 'show_config', 'shuffle', 'sign', 'signbit', 'signedinteger', 'silent_list', 'sin', 'sinc', 'single', 'singlecomplex', 'sinh', 'six', 'size', 'slogdet', 'slopes', 'solve', 'sometrue', 'sort', 'sort_complex', 'source', 'spacing', 'specgram', 'spectral', 'split', 'spring', 'spy', 'sqrt', 'square', 'squeeze', 'stack', 'stackplot', 'standard_cauchy', 'standard_exponential', 'standard_gamma', 'standard_normal', 'standard_t', 'std', 'stem', 'step', 'stineman_interp', 'str_', 'streamplot', 'string0', 'string_', 'strpdate2num', 'style', 'subplot', 'subplot2grid', 'subplot_tool', 'subplots', 'subplots_adjust', 'subtract', 'sum', 'summer', 'suptitle', 'svd', 'swapaxes', 'switch_backend', 'sys', 'table', 'take', 'tan', 'tanh', 'tensordot', 'tensorinv', 'tensorsolve', 'test', 'text', 'thetagrids', 'tick_params', 'ticklabel_format', 'tight_layout', 'tile', 'timedelta64', 'title', 'trace', 'transpose', 'trapz', 'tri', 'triangular', 'tricontour', 'tricontourf', 'tril', 'tril_indices', 'tril_indices_from', 'trim_zeros', 'tripcolor', 'triplot', 'triu', 'triu_indices', 'triu_indices_from', 'true_divide', 'trunc', 'twinx', 'twiny', 'typeDict', 'typeNA', 'typecodes', 'typename', 'types', 'ubyte', 'ufunc', 'uint', 'uint0', 'uint16', 'uint32', 'uint64', 'uint8', 'uintc', 'uintp', 'ulonglong', 'unicode0', 'unicode_', 'unicode_literals', 'uniform', 'uninstall_repl_displayhook', 'union1d', 'unique', 'unpackbits', 'unravel_index', 'unsignedinteger', 'unwrap', 'ushort', 'vander', 'var', 'vdot', 'vector_lengths', 'vectorize', 'view', 'violinplot', 'viridis', 'vlines', 'void', 'void0', 'vonmises', 'vsplit', 'vstack', 'waitforbuttonpress', 'wald', 'warnings', 'weibull', 'where', 'who', 'window_hanning', 'window_none', 'winter', 'xcorr', 'xkcd', 'xlabel', 'xlim', 'xscale', 'xticks', 'ylabel', 'ylim', 'yscale', 'yticks', 'zeros', 'zeros_like', 'zipf']

2.目錄書籤系統

目錄中不要帶有空格,不然會出現錯誤:

%bookmark bk E:/python data processing
UsageError: %bookmark: too many arguments

%bookmark bk E:/python_data_processing

%bookmark -l
Current bookmarks:
bk   -> E:/python_data_processing

3.交互式調試器

用canopy運行以下代碼,會卡死(可能是運行時間過長),最後用Ctrl+C結束。

run -d ipython_bug.py
Breakpoint 1 at e:\enthought\book\ch03\ipython_bug.py:1
NOTE: Enter 'c' at the ipdb>  prompt to continue execution.

但是用cmd->ipython則能正常使用:
這裏寫圖片描述

4.IPython HTML Notebook

現已更改jupyter,個人感覺並沒有太好用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章