在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 教程/ Python/ Pandas 使用 (2)
標(biāo)準(zhǔn)庫 (4)
如何成為 Python 高手
標(biāo)準(zhǔn)庫 (6)
標(biāo)準(zhǔn)庫 (3)
類(2)
Pandas 使用 (2)
xml
用 tornado 做網(wǎng)站 (5)
文件(1)
練習(xí)
列表(3)
從小工到專家
除法
錯(cuò)誤和異常 (2)
函數(shù)(1)
用 tornado 做網(wǎng)站 (7)
為做網(wǎng)站而準(zhǔn)備
函數(shù)練習(xí)
標(biāo)準(zhǔn)庫 (8)
Pandas 使用 (1)
回顧 list 和 str
字典(1)
用 tornado 做網(wǎng)站 (3)
字符串(1)
函數(shù)(2)
寫一個(gè)簡單的程序
將數(shù)據(jù)存入文件
語句(5)
SQLite 數(shù)據(jù)庫
集成開發(fā)環(huán)境(IDE)
集合(1)
類(1)
用 tornado 做網(wǎng)站 (6)
用 tornado 做網(wǎng)站 (2)
自省
語句(4)
錯(cuò)誤和異常 (1)
用 tornado 做網(wǎng)站 (4)
集合(2)
列表(1)
標(biāo)準(zhǔn)庫 (1)
生成器
mysql 數(shù)據(jù)庫 (1)
第三方庫
實(shí)戰(zhàn)
運(yùn)算符
類(3)
字典(2)
語句(1)
數(shù)和四則運(yùn)算
語句(2)
文件(2)
MySQL 數(shù)據(jù)庫 (2)
電子表格
迭代器
mongodb 數(shù)據(jù)庫 (1)
特殊方法 (2)
特殊方法 (1)
字符編碼
編寫模塊
用 tornado 做網(wǎng)站 (1)
標(biāo)準(zhǔn)庫 (5)
函數(shù)(4)
類(5)
字符串(2)
關(guān)于 Python 的故事
函數(shù)(3)
字符串(4)
處理股票數(shù)據(jù)
常用數(shù)學(xué)函數(shù)和運(yùn)算優(yōu)先級
字符串(3)
為計(jì)算做準(zhǔn)備
多態(tài)和封裝
類(4)
迭代
語句(3)
錯(cuò)誤和異常 (3)
分析 Hello
Python 安裝
標(biāo)準(zhǔn)庫 (2)
列表(2)
元組

Pandas 使用 (2)

特別向讀者生命,本教程因?yàn)槠拗疲荒軐⒂嘘P(guān) pandas 的內(nèi)容完全詳細(xì)講述,只能“拋磚引玉”,向大家做一個(gè)簡單介紹,說明其基本使用方法。當(dāng)讀者在實(shí)踐中使用的時(shí)候,如果遇到問題,可以結(jié)合相關(guān)文檔或者 google 來解決。

讀取 csv 文件

關(guān)于 csv 文件

csv 是一種通用的、相對簡單的文件格式,在表格類型的數(shù)據(jù)中用途很廣泛,很多關(guān)系型數(shù)據(jù)庫都支持這種類型文件的導(dǎo)入導(dǎo)出,并且 excel 這種常用的數(shù)據(jù)表格也能和 csv 文件之間轉(zhuǎn)換。

逗號分隔值(Comma-Separated Values,CSV,有時(shí)也稱為字符分隔值,因?yàn)榉指糇址部梢圆皇嵌禾枺?,其文件以純文本形式存儲表格?shù)據(jù)(數(shù)字和文本)。純文本意味著該文件是一個(gè)字符序列,不含必須象二進(jìn)制數(shù)字那樣被解讀的數(shù)據(jù)。CSV 文件由任意數(shù)目的記錄組成,記錄間以某種換行符分隔;每條記錄由字段組成,字段間的分隔符是其它字符或字符串,最常見的是逗號或制表符。通常,所有記錄都有完全相同的字段序列。

從上述維基百科的敘述中,重點(diǎn)要解讀出“字段間分隔符”“最常見的是逗號或制表符”,當(dāng)然,這種分隔符也可以自行制定。比如下面這個(gè)我命名為 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

其實(shí),這個(gè)文件要表達(dá)的事情是(如果轉(zhuǎn)化為表格形式):

http://wiki.jikexueyuan.com/project/start-learning-python/images/31006.png" alt="" />

普通方法讀取

最簡單、最直接的就是 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 中還有一個(gè) csv 的標(biāo)準(zhǔn)庫,足可見 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']

什么時(shí)候也不要忘記這種最佳學(xué)習(xí)方法。從上面結(jié)果可以看出,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']

算是稍有改善。

用 Pandas 讀取

如果對上面的結(jié)果都有點(diǎn)不滿意的話,那么看看 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

看了這樣的結(jié)果,你還不感覺驚訝嗎?你還不喜歡上 Pandas 嗎?這是多么精妙的顯示。它是什么?它就是一個(gè) DataFrame 數(shù)據(jù)。

還有另外一種方法:

>>> 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

如果你有足夠的好奇心來研究這個(gè)名叫 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']

一個(gè)一個(gè)瀏覽一下,通過名字可以直到那個(gè)方法或者屬性的大概,然后就可以根據(jù)你的喜好和需要,試一試:

>>> marks.index
Int64Index([0, 1, 2, 3], dtype=int64)
>>> marks.columns
Index([name, physics, python, math, english], dtype=object)
>>> marks['name'][1]
'Facebook'

這幾個(gè)是讓你回憶一下上一節(jié)的。從 DataFrame 對象的屬性和方法中找一個(gè),再嘗試:

>>> 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"的值排隊(duì),結(jié)果也是很讓人滿意的。下面幾個(gè)操作,也是常用到的,并且秉承了 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

可以說,當(dāng)你已經(jīng)掌握了通過 dir() 和 help() 查看對象的方法和屬性時(shí),就已經(jīng)掌握了 pandas 的用法,其實(shí)何止 pandas,其它對象都是如此。

讀取其它格式數(shù)據(jù)

csv 是常用來存儲數(shù)據(jù)的格式之一,此外常用的還有 MS excel 格式的文件,以及 json 和 xml 格式的數(shù)據(jù)等。它們都可以使用 pandas 來輕易讀取。

.xls 或者 .xlsx

在下面的結(jié)果中尋覓一下,有沒有跟 excel 有關(guān)的方法?

>>> 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() 的方法(在網(wǎng)上查詢,有的資料說有 read_xls() 方法,那時(shí)老黃歷了),但是有 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

我這里少了一個(gè)模塊,看報(bào)錯(cuò)提示, 用pip 安裝 openpyxl 模塊:sudo pip install openpyxl。繼續(xù):

>>> 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

結(jié)果中,columns 的名字與前面 csv 結(jié)果不一樣,數(shù)據(jù)部分是同樣結(jié)果。從結(jié)果中可以看到,sheet1 也是一個(gè) DataFrame 對象。

對于單個(gè)的 DataFrame 對象,如何通過屬性和方法進(jìn)行操作,如果讀者理解了本教程從一開始就貫穿進(jìn)來的思想——利用 dir() 和 help() 或者到官方網(wǎng)站,看文檔!——此時(shí)就能比較輕松地進(jìn)行各種操作了。下面的舉例,純屬是為了增加篇幅和向讀者做一些誘惑性廣告,或者給懶惰者看看。當(dāng)然,肯定是不完全,也不能在實(shí)踐中照搬。基本方法還在剛才交代過的思想。

如果遇到了 json 或者 xml 格式的數(shù)據(jù)怎么辦呢?直接使用本教程第貳季第陸章中《標(biāo)準(zhǔn)庫 (7)《標(biāo)準(zhǔn)庫 (8)》中的方法,再結(jié)合 Series 或者 DataFrame 數(shù)據(jù)特點(diǎn)讀取。

此外,還允許從數(shù)據(jù)庫中讀取數(shù)據(jù),首先就是使用本教程第貳季第柒章中闡述的各種數(shù)據(jù)庫(《MySQL 數(shù)據(jù)庫 (1)》,《MongoDB 數(shù)據(jù)庫》,《SQLite 數(shù)據(jù)庫》)連接和讀取方法,將相應(yīng)數(shù)據(jù)查詢出來,并且將結(jié)果(結(jié)果通常是列表或者元組類型,或者是字符串)按照前面講述的 Series 或者 DataFrame 類型數(shù)據(jù)進(jìn)行組織,然后就可以對其操作。


總目錄   |   上節(jié):Pandas 使用 (1)   |   下節(jié):Pandas 使用 (3)

如果你認(rèn)為有必要打賞我,請通過支付寶:qiwsir@126.com,不勝感激。

上一篇:文件(2)下一篇:從小工到專家