<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                特別向讀者生命,本教程因為篇幅限制,不能將有關pandas的內容完全詳細講述,只能“拋磚引玉”,向大家做一個簡單介紹,說明其基本使用方法。當讀者在實踐中使用的時候,如果遇到問題,可以結合相關文檔或者google來解決。 ## [](https://github.com/qiwsir/StarterLearningPython/blob/master/312.md#讀取csv文件)讀取csv文件 ### [](https://github.com/qiwsir/StarterLearningPython/blob/master/312.md#關于csv文件)關于csv文件 csv是一種通用的、相對簡單的文件格式,在表格類型的數據中用途很廣泛,很多關系型數據庫都支持這種類型文件的導入導出,并且excel這種常用的數據表格也能和csv文件之間轉換。 > 逗號分隔值(Comma-Separated Values,CSV,有時也稱為字符分隔值,因為分隔字符也可以不是逗號),其文件以純文本形式存儲表格數據(數字和文本)。純文本意味著該文件是一個字符序列,不含必須象二進制數字那樣被解讀的數據。CSV文件由任意數目的記錄組成,記錄間以某種換行符分隔;每條記錄由字段組成,字段間的分隔符是其它字符或字符串,最常見的是逗號或制表符。通常,所有記錄都有完全相同的字段序列。 從上述維基百科的敘述中,重點要解讀出“字段間分隔符”“最常見的是逗號或制表符”,當然,這種分隔符也可以自行制定。比如下面這個我命名為marks.csv的文件,就是用逗號(必須是半角的)作為分隔符: ~~~ name,physics,python,math,english Google,100,100,25,12 Facebook,45,54,44,88 Twitter,54,76,13,91 Yahoo,54,452,26,100 ~~~ 其實,這個文件要表達的事情是(如果轉化為表格形式): [![](https://box.kancloud.cn/2015-09-07_55ed60cdedeb8.png)](https://github.com/qiwsir/StarterLearningPython/blob/master/3images/31006.png) ### [](https://github.com/qiwsir/StarterLearningPython/blob/master/312.md#普通方法讀取)普通方法讀取 最簡單、最直接的就是open()打開文件: ~~~ >>> with open("./marks.csv") as f: ... for line in f: ... print line ... name,physics,python,math,english Google,100,100,25,12 Facebook,45,54,44,88 Twitter,54,76,13,91 Yahoo,54,452,26,100 ~~~ 此方法可以,但略顯麻煩。 python中還有一個csv的標準庫,足可見csv文件的使用頻繁了。 ~~~ >>> import csv >>> dir(csv) ['Dialect', 'DictReader', 'DictWriter', 'Error', 'QUOTE_ALL', 'QUOTE_MINIMAL', 'QUOTE_NONE', 'QUOTE_NONNUMERIC', 'Sniffer', 'StringIO', '_Dialect', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', 'excel', 'excel_tab', 'field_size_limit', 'get_dialect', 'list_dialects', 're', 'reader', 'reduce', 'register_dialect', 'unregister_dialect', 'writer'] ~~~ 什么時候也不要忘記這種最佳學習方法。從上面結果可以看出,csv模塊提供的屬性和方法。僅僅就讀取本例子中的文件: ~~~ >>> import csv >>> csv_reader = csv.reader(open("./marks.csv")) >>> for row in csv_reader: ... print row ... ['name', 'physics', 'python', 'math', 'english'] ['Google', '100', '100', '25', '12'] ['Facebook', '45', '54', '44', '88'] ['Twitter', '54', '76', '13', '91'] ['Yahoo', '54', '452', '26', '100'] ~~~ 算是稍有改善。 ### [](https://github.com/qiwsir/StarterLearningPython/blob/master/312.md#用pandas讀取)用Pandas讀取 如果對上面的結果都有點不滿意的話,那么看看Pandas的效果: ~~~ >>> import pandas as pd >>> marks = pd.read_csv("./marks.csv") >>> marks name physics python math english 0 Google 100 100 25 12 1 Facebook 45 54 44 88 2 Twitter 54 76 13 91 3 Yahoo 54 452 26 100 ~~~ 看了這樣的結果,你還不感覺驚訝嗎?你還不喜歡上Pandas嗎?這是多么精妙的顯示。它是什么?它就是一個DataFrame數據。 還有另外一種方法: ~~~ >>> pd.read_table("./marks.csv", sep=",") name physics python math english 0 Google 100 100 25 12 1 Facebook 45 54 44 88 2 Twitter 54 76 13 91 3 Yahoo 54 452 26 100 ~~~ 如果你有足夠的好奇心來研究這個名叫DataFrame的對象,可以這樣: ~~~ >>> dir(marks) ['T', '_AXIS_ALIASES', '_AXIS_NAMES', '_AXIS_NUMBERS', '__add__', '__and__', '__array__', '__array_wrap__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__div__', '__doc__', '__eq__', '__floordiv__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__or__', '__pow__', '__radd__', '__rdiv__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__weakref__', '__xor__', '_agg_by_level', '_align_frame', '_align_series', '_apply_broadcast', '_apply_raw', '_apply_standard', '_auto_consolidate', '_bar_plot', '_boolean_set', '_box_item_values', '_clear_item_cache', '_combine_const', '_combine_frame', '_combine_match_columns', '_combine_match_index', '_combine_series', '_combine_series_infer', '_compare_frame', '_consolidate_inplace', '_constructor', '_count_level', '_cov_helper', '_data', '_default_stat_axis', '_expand_axes', '_from_axes', '_get_agg_axis', '_get_axis', '_get_axis_name', '_get_axis_number', '_get_item_cache', '_get_numeric_data', '_getitem_array', '_getitem_multilevel', '_helper_csvexcel', '_het_axis', '_indexed_same', '_init_dict', '_init_mgr', '_init_ndarray', '_is_mixed_type', '_item_cache', '_ix', '_join_compat', '_reduce', '_reindex_axis', '_reindex_columns', '_reindex_index', '_reindex_with_indexers', '_rename_columns_inplace', '_rename_index_inplace', '_sanitize_column', '_series', '_set_axis', '_set_item', '_set_item_multiple', '_shift_indexer', '_slice', '_unpickle_frame_compat', '_unpickle_matrix_compat', '_verbose_info', '_wrap_array', 'abs', 'add', 'add_prefix', 'add_suffix', 'align', 'append', 'apply', 'applymap', 'as_matrix', 'asfreq', 'astype', 'axes', 'boxplot', 'clip', 'clip_lower', 'clip_upper', 'columns', 'combine', 'combineAdd', 'combineMult', 'combine_first', 'consolidate', 'convert_objects', 'copy', 'corr', 'corrwith', 'count', 'cov', 'cummax', 'cummin', 'cumprod', 'cumsum', 'delevel', 'describe', 'diff', 'div', 'dot', 'drop', 'drop_duplicates', 'dropna', 'dtypes', 'duplicated', 'fillna', 'filter', 'first_valid_index', 'from_csv', 'from_dict', 'from_items', 'from_records', 'get', 'get_dtype_counts', 'get_value', 'groupby', 'head', 'hist', 'icol', 'idxmax', 'idxmin', 'iget_value', 'index', 'info', 'insert', 'irow', 'iteritems', 'iterkv', 'iterrows', 'ix', 'join', 'last_valid_index', 'load', 'lookup', 'mad', 'max', 'mean', 'median', 'merge', 'min', 'mul', 'ndim', 'pivot', 'pivot_table', 'plot', 'pop', 'prod', 'product', 'quantile', 'radd', 'rank', 'rdiv', 'reindex', 'reindex_axis', 'reindex_like', 'rename', 'rename_axis', 'reorder_levels', 'reset_index', 'rmul', 'rsub', 'save', 'select', 'set_index', 'set_value', 'shape', 'shift', 'skew', 'sort', 'sort_index', 'sortlevel', 'stack', 'std', 'sub', 'sum', 'swaplevel', 'tail', 'take', 'to_csv', 'to_dict', 'to_excel', 'to_html', 'to_panel', 'to_records', 'to_sparse', 'to_string', 'to_wide', 'transpose', 'truncate', 'unstack', 'values', 'var', 'xs'] ~~~ 一個一個瀏覽一下,通過名字可以直到那個方法或者屬性的大概,然后就可以根據你的喜好和需要,試一試: ~~~ >>> marks.index Int64Index([0, 1, 2, 3], dtype=int64) >>> marks.columns Index([name, physics, python, math, english], dtype=object) >>> marks['name'][1] 'Facebook' ~~~ 這幾個是讓你回憶一下上一節的。從DataFrame對象的屬性和方法中找一個,再嘗試: ~~~ >>> marks.sort(column="python") name physics python math english 1 Facebook 45 54 44 88 2 Twitter 54 76 13 91 0 Google 100 100 25 12 3 Yahoo 54 452 26 100 ~~~ 按照豎列"python"的值排隊,結果也是很讓人滿意的。下面幾個操作,也是常用到的,并且秉承了python的一貫方法: ~~~ >>> marks[:1] name physics python math english 0 Google 100 100 25 12 >>> marks[1:2] name physics python math english 1 Facebook 45 54 44 88 >>> marks["physics"] 0 100 1 45 2 54 3 54 Name: physics ~~~ 可以說,當你已經掌握了通過dir()和help()查看對象的方法和屬性時,就已經掌握了pandas的用法,其實何止pandas,其它對象都是如此。 ## [](https://github.com/qiwsir/StarterLearningPython/blob/master/312.md#讀取其它格式數據)讀取其它格式數據 csv是常用來存儲數據的格式之一,此外常用的還有MS excel格式的文件,以及json和xml格式的數據等。它們都可以使用pandas來輕易讀取。 ### [](https://github.com/qiwsir/StarterLearningPython/blob/master/312.md#xls或者xlsx).xls或者.xlsx 在下面的結果中尋覓一下,有沒有跟excel有關的方法? ~~~ >>> dir(pd) ['DataFrame', 'DataMatrix', 'DateOffset', 'DateRange', 'ExcelFile', 'ExcelWriter', 'Factor', 'HDFStore', 'Index', 'Int64Index', 'MultiIndex', 'Panel', 'Series', 'SparseArray', 'SparseDataFrame', 'SparseList', 'SparsePanel', 'SparseSeries', 'SparseTimeSeries', 'TimeSeries', 'WidePanel', '__builtins__', '__doc__', '__docformat__', '__file__', '__name__', '__package__', '__path__', '__version__', '_engines', '_sparse', '_tseries', 'concat', 'core', 'crosstab', 'datetime', 'datetools', 'debug', 'ewma', 'ewmcorr', 'ewmcov', 'ewmstd', 'ewmvar', 'ewmvol', 'fama_macbeth', 'groupby', 'info', 'io', 'isnull', 'lib', 'load', 'merge', 'notnull', 'np', 'ols', 'pivot', 'pivot_table', 'read_clipboard', 'read_csv', 'read_table', 'reset_printoptions', 'rolling_apply', 'rolling_corr', 'rolling_corr_pairwise', 'rolling_count', 'rolling_cov', 'rolling_kurt', 'rolling_max', 'rolling_mean', 'rolling_median', 'rolling_min', 'rolling_quantile', 'rolling_skew', 'rolling_std', 'rolling_sum', 'rolling_var', 'save', 'set_eng_float_format', 'set_printoptions', 'sparse', 'stats', 'tools', 'util', 'value_range', 'version'] ~~~ 雖然沒有類似`read_csv()`的方法(在網上查詢,有的資料說有`read_xls()`方法,那時老黃歷了),但是有`ExcelFile`類,于是乎: ~~~ >>> xls = pd.ExcelFile("./marks.xlsx") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/pymodules/python2.7/pandas/io/parsers.py", line 575, in __init__ from openpyxl import load_workbook ImportError: No module named openpyxl ~~~ 我這里少了一個模塊,看報錯提示,用pip安裝openpyxl模塊:`sudo pip install openpyxl`。繼續: ~~~ >>> xls = pd.ExcelFile("./marks.xlsx") >>> dir(xls) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parse_xls', '_parse_xlsx', 'book', 'parse', 'path', 'sheet_names', 'use_xlsx'] >>> xls.sheet_names ['Sheet1', 'Sheet2', 'Sheet3'] >>> sheet1 = xls.parse("Sheet1") >>> sheet1 0 1 2 3 4 0 5 100 100 25 12 1 6 45 54 44 88 2 7 54 76 13 91 3 8 54 452 26 100 ~~~ 結果中,columns的名字與前面csv結果不一樣,數據部分是同樣結果。從結果中可以看到,sheet1也是一個DataFrame對象。 對于單個的DataFrame對象,如何通過屬性和方法進行操作,如果讀者理解了本教程從一開始就貫穿進來的思想——利用dir()和help()或者到官方網站,看文檔!——此時就能比較輕松地進行各種操作了。下面的舉例,純屬是為了增加篇幅和向讀者做一些誘惑性廣告,或者給懶惰者看看。當然,肯定是不完全,也不能在實踐中照搬。基本方法還在剛才交代過的思想。 如果遇到了json或者xml格式的數據怎么辦呢?直接使用本教程第貳季第陸章中[《標準庫(7)](https://github.com/qiwsir/StarterLearningPython/blob/master/226.md)和[《標準庫(8)》](https://github.com/qiwsir/StarterLearningPython/blob/master/227.md)中的方法,再結合Series或者DataFrame數據特點讀取。 此外,還允許從數據庫中讀取數據,首先就是使用本教程第貳季第柒章中闡述的各種數據庫([《MySQL數據庫(1)》](https://github.com/qiwsir/StarterLearningPython/blob/master/230.md),[《MongoDB數據庫》](https://github.com/qiwsir/StarterLearningPython/blob/master/232.md),[《SQLite數據庫》](https://github.com/qiwsir/StarterLearningPython/blob/master/233.md))連接和讀取方法,將相應數據查詢出來,并且將結果(結果通常是列表或者元組類型,或者是字符串)按照前面講述的Series或者DataFrame類型數據進行組織,然后就可以對其操作。``
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看