Pandas 105:更多進階資料框技巧

如何合併資料框

Yao-Jen Kuo
數聚點文摘
Published in
8 min readOct 2, 2019

--

Photo by Roman Kraft on Unsplash

Pandas provides various facilities for easily combining together Series or DataFrame with various kinds of set logic for the indexes and relational algebra functionality in the case of join / merge-type operations.

https://pandas.pydata.org/pandas-docs/stable

TL; DR 摘要

這個小節簡介 Pandas 套件中常用來合併資料框的四個常用函數與方法,她們分別是 concat、append、merge 與 join;concat 與 merge 是簡單合併以及聯結的常規函數,append 與 join 則是建構於資料框的方法,目的是簡化合併的語法。

在這個小節中我們常會需要在一個 Jupyter Notebook 的儲存格中顯示多個物件,但為了漂亮的資料框外觀不想使用 print() 函數,於是在筆記本的第一個儲存格加入額外設定,讓原本預設只顯示儲存格最後一個物件更改為顯示所有物件。

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

著手進行一個資料科學專案的過程中,組合不同來源的資料集是極為常見的操作,這些操作可能僅是將兩個不同的資料非常直觀的串聯,也有可能是更複雜的資料庫表格聯結,Pandas 套件有四種常用函數或方法能夠協助使用者完成不同資料源的組合:

  • pd.concat()
  • df.append()
  • pd.merge()
  • df.join()

簡單合併 pd.concat()

pd.concat() 函數與 NumPy 套件中的 np.concatenate() 相似,利用 axis 參數可指定垂直或水平方向地合併兩個資料框,預設 axis=0 為垂直合併。

--

--