Python For Data Analysis學習之路

來源:互聯網
上載者:User
在引言章節裡,介紹了MovieLens 1M資料集的處理樣本。書中介紹該資料集來自GroupLens Research(),該地址會直接跳轉到,這裡面提供了來自MovieLens網站的各種評估資料集,可以下載相應的壓縮包,我們需要的MovieLens 1M資料集也在裡面。

下載解壓後的檔案夾如下:

這三個dat表都會在樣本中用到。我所閱讀的《Python For Data Analysis》中文版(PDF)是2014年第一版的,裡面所有樣本都是基於Python 2.7和pandas 0.8.2所寫的,而我安裝的是Python 3.5.2與pandas 0.20.2,裡面的一些函數與方法會有較大的不同,有些是新版本中參數改變了,而有些是新版本裡棄用了某些舊版本的函數,這導致我運行按照書中範例程式碼時,會遇到一些Error和Warning。在測試MovieLens 1M資料集代碼時,在和一樣我的配置環境下,會遇到如下幾個問題。

  • 在將dat資料讀入到pandas DataFrame對象中時,書中給出代碼為:

    users = pd.read_table('ml-1m/users.dat', sep='::', header=None, names=unames)rnames = ['user_id', 'movie_id', 'rating', 'timestamp']ratings = pd.read_table('ml-1m/ratings.dat', sep='::', header=None, names=rnames)mnames = ['movie_id', 'title', 'genres']movies = pd.read_table('ml-1m/movies.dat', sep='::', header=None, names=mnames)

    直接運行會出現Warning:

    F:/python/HelloWorld/DataAnalysisByPython-1.py:4: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'.  users = pd.read_table('ml-1m/users.dat', sep='::', header=None, names=unames)F:/python/HelloWorld/DataAnalysisByPython-1.py:7: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'.  ratings = pd.read_table('ml-1m/ratings.dat', sep='::', header=None, names=rnames)F:/python/HelloWorld/DataAnalysisByPython-1.py:10: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'.  movies = pd.read_table('ml-1m/movies.dat', sep='::', header=None, names=mnames)

    雖然也能運行,但是作為完美強迫症的我還是想要解決這個Warning。這個警告是說因為'C'引擎不支援,只能退回到'Python'引擎,而剛好pandas.read_table方法裡有個engine參數,用來設定使用哪種解析引擎,有'C'和'Python'這兩個選項。既然'C'引擎不支援,我們只需把engine設為'Python'就可以了。

    users = pd.read_table('ml-1m/users.dat', sep='::', header=None, names=unames, engine = 'python')rnames = ['user_id', 'movie_id', 'rating', 'timestamp']ratings = pd.read_table('ml-1m/ratings.dat', sep='::', header=None, names=rnames, engine = 'python')mnames = ['movie_id', 'title', 'genres']movies = pd.read_table('ml-1m/movies.dat', sep='::', header=None, names=mnames, engine = 'python')

  • 使用pivot_table方法來對彙總後的資料按性別計算每部電影的平均得分,書中給出的代碼為:

    mean_ratings = data.pivot_table('rating', rows='title', cols='gender', aggfunc='mean')

    直接運行會報錯,這段代碼無法運行:

    Traceback (most recent call last):  File "F:/python/HelloWorld/DataAnalysisByPython-1.py", line 19, in <module>mean_ratings = data.pivot_table('rating', rows='title', cols='gender', aggfunc='mean')TypeError: pivot_table() got an unexpected keyword argument 'rows'

    TypeError說明這裡的'rows'參數並不是方法裡可用的關鍵字參數,這是這麼回事呢?去官網上查了下pandas的API使用文檔(),發現是因為0.20.2版的pandas.pivot_table裡關鍵字參數變了,為了實現同樣效果,只需把rows換成index就可以了,同時也沒有cols參數,要用columns來代替。

    mean_ratings = data.pivot_table('rating', index='title', columns='gender', aggfunc='mean')

  • 為了瞭解女性觀眾最喜歡的電影,使用DataFrame的方法對F列進行降序排序,書中的範例程式碼為:

    top_female_ratings = mean_ratings.sort_index(by='F', ascending=False)

    這裡也只是給出一個Warning,並不會干擾程式進行:

    F:/python/HelloWorld/DataAnalysisByPython-1.py:32: FutureWarning: by argument to sort_index is deprecated, pls use .sort_values(by=...)  top_female_ratings = mean_ratings.sort_index(by='F', ascending=False)

    這裡是說進行排序的sort_index方法在將來語言或者庫中可能發生改變,建議改為使用sort_values。在API使用文檔中,對pandas.DataFrame.sort_index的描述為“Sort object by labels (along an axis)”,而對pandas.DataFrame.sort_values的描述為“Sort by the values along either axis”,兩者能達到同樣效果,那我就直接替換成sort_values就可以了。在後面的“計算評分分歧”中也會用到sort_index,也可以替換成sort_values。

    top_female_ratings = mean_ratings.sort_values(by='F', ascending=False)

  • 最後一個錯誤還是和排序有關。在“計算評分分歧”中計算得分資料的標準差之後,根據過濾後的值對Series進行降序排序,書中的代碼為:

    print(rating_std_by_title.order(ascending=False)[:10])

    這裡的錯誤是:

    Traceback (most recent call last):  File "F:/python/HelloWorld/DataAnalysisByPython-1.py", line 47, in <module>print(rating_std_by_title.order(ascending=False)[:10])  File "E:\Program Files\Python35\lib\site-packages\pandas\core\generic.py", line 2970, in __getattr__return object.__getattribute__(self, name)AttributeError: 'Series' object has no attribute 'order'

    居然已經沒有這個order的方法了,只好去API文檔中找替代的方法用。有兩個,sort_index和sort_values,這和DataFrame中的方法一樣,為了保險起見,我選擇使用sort_values:

    print(rating_std_by_title.sort_values(ascending=False)[:10]

    得到的結果和資料展示的結果一樣,可以放心使用。

第三方庫不同版本間的差異還是挺明顯的,建議是使用最新的版本,在使用時配合官網網站上的API使用文檔,輕鬆解決各類問題~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.