Pandas 的groupby操作

來源:互聯網
上載者:User

標籤:

本文和大家分享的主要是Pandas 的groupby操作相關內容,一起來看看吧,希望對大家學習Pandas有所協助。 在做資料分析的時候,我們的資料一般從資料庫來,那麼就涉及到groupby操作。例如,我們要預測一個居民小區的未來一段時間的電費,那麼就要將資料按照小區groupby,然後按照時間排序,這裡groupby操作可完美的完成這個任務。 假設資料表cellfee結構為: reportdate, cidyid, cellid, fee。 讀取表資料 import pandas as pdfrom sqlalchemy import create_engine# default engine = create_engine(’mysql+pymysql://ledao:[email protected]/pandas_learn’) original_data = pd.read_sql_table(’cellfee’, engine) original_data groupby分組匯總指定類別的所有資料 for k, v in original_data.groupby([original_data[’cityid’], original_data[’cellid’]]): print(’key: {}, type is {}’.format(k, type(k))) print(’vale:\n {}, \ntype is {}’.format(v, type(v))) 上述的代碼的結果為: key: (’1’, ’1’), type is vale: reportdate cityid cellid fee 0 2017-07-20 1 1 10.0 1 2017-07-21 1 1 10.0 2 2017-07-22 1 1 10.0 3 2017-07-23 1 1 10.0, type is 通過一個簡單的groupby函數,我們就能將資料庫中以列儲存的資料根據分組要求全部匯總到一個形成一個DataFrame。後續對分組形成的DataFrame可以做形成特徵向量,排序,再繼續匯總等常見的資料分析的操作。 在groupby的操作上,我只服氣scala、kotlin的模式,即groupby加map(flatMap),希望pandas以後也會支援這種函數式的操作。 agg函數 除了groupby的結果通過for遍曆之後,Pandas也提供了agg函數。主要用於對具體的列的操作,類似sql。來源:簡書

Pandas 的groupby操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.