Python數(shù)據(jù)處理的三個實用技巧分享
我使用的 Pandas 版本如下,順便也導入 Pandas 庫。
>>> import pandas as pd >>> pd.__version__ '0.25.1'
在開始前先確保解釋器和數(shù)據(jù)集在同一目錄下:
>>> import os >>> os.chdir('D://source/dataset') # 這是我的數(shù)據(jù)集所在目錄 >>> os.listdir() # 確認此目錄已經(jīng)存在 IMDB-Movie-Data 數(shù)據(jù)集 ['drinksbycountry.csv', 'IMDB-Movie-Data.csv', 'movietweetings', 'titanic_eda_data.csv', 'titanic_train_data.csv']
準備工作就位后,正式開始數(shù)據(jù)處理技巧之旅。
1 Pandas 移除某列
導入數(shù)據(jù)
>>> df = pd.read_csv("IMDB-Movie-Data.csv") >>> df.head(1) # 導入并顯示第一行 ? ?Rank ? ? ? ? ? ? ? ? ? ?Title ? ? ? ? ? ? ? ? ? ?Genre ?... ? Votes Revenue (Millions) Metascore 0 ? ? 1 ?Guardians of the Galaxy ?Action,Adventure,Sci-Fi ?... ?757074 ? ? ? ? ? ? 333.13 ? ? ?76.0 [1 rows x 12 columns]
使用 pop 方法移除指定列:
>>> meta = df.pop("Title").to_frame() # 移除 Title 列
確認是否已被移除:
>>> df.head(1) # df 變?yōu)?11列 ? ?Rank ? ? ? ? ? ? ? ? ? ?Genre ?... Revenue (Millions) Metascore 0 ? ? 1 ?Action,Adventure,Sci-Fi ?... ? ? ? ? ? ? 333.13 ? ? ?76.0 [1 rows x 11 columns]
2 統(tǒng)計標題單詞數(shù)
pop 后得到 meta,顯示 meta 前 3 行:
>>> meta.head(3) Title 0 Guardians of the Galaxy 1 Prometheus 2 Split
標題是由單詞組成,中間用空格分隔。
# .str.count(" ") + 1 得到單詞個數(shù) >>> meta["words_count"] = meta["Title"].str.count(" ") + 1 >>> meta.head(3) # words_count 列代表單詞個數(shù) Title words_count 0 Guardians of the Galaxy 4 1 Prometheus 1 2 Split 1
3 Genre 頻次統(tǒng)計
下面統(tǒng)計電影 Genre 的頻次,
>>> vc = df["Genre"].value_counts()
下面顯示電影 Genre 的 Top5 ,最高頻為出現(xiàn) 50 次的 Action,Adventure,Sci-Fi 類,次之為 48 次的 Drama 類:
>>> vc.head() Action,Adventure,Sci-Fi 50 Drama 48 Comedy,Drama,Romance 35 Comedy 32 Drama,Romance 31 Name: Genre, dtype: int64
展示 Top5 的餅狀圖:
>>> import matplotlib.pyplot as plt >>> vc[:5].plot(kind='pie') <matplotlib.axes._subplots.AxesSubplot object at 0x000001D65B114948> >>> plt.show()
到此這篇關(guān)于Python數(shù)據(jù)處理的三個實用技巧分享的文章就介紹到這了,更多相關(guān)Python 數(shù)據(jù)處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中用startswith()函數(shù)判斷字符串開頭的教程
這篇文章主要介紹了Python中用startswith()函數(shù)判斷字符串開頭的教程,startswith()函數(shù)的使用是Python學習中的基礎(chǔ)知識,本文列舉了一些不同情況下的使用結(jié)果,需要的朋友可以參考下2015-04-04解決windows下命令行執(zhí)行python3失效,會打開應(yīng)用商店問題
這篇文章主要介紹了解決windows下命令行執(zhí)行python3失效,會打開應(yīng)用商店問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02Python?return函數(shù)返回值類型和幫助函數(shù)使用教程
這篇文章主要為大家介紹了Python?return函數(shù)返回值類型和幫助函數(shù)使用教程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06Python實現(xiàn)監(jiān)視程序的內(nèi)存使用情況
我們使用Python和它的數(shù)據(jù)處理庫套件進行大量數(shù)據(jù)處理時候,可能使用了大量的計算資源,那么如何監(jiān)視程序的內(nèi)存使用情況就顯得尤為重要,下面我們就來了解一下具體實現(xiàn)方法吧2023-12-12python實現(xiàn)自動網(wǎng)頁截圖并裁剪圖片
這篇文章主要為大家詳細介紹了python實現(xiàn)自動網(wǎng)頁截圖并裁剪圖片,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07