Try   HackMD

Merging DataFrames with pandas

tags: Datacamp python panda data science Data Manipulation with Python

作者:何彥南
Datacamp 課程: Merging DataFrames with pandas

注意:

  1. 以下df 為 pandas 的 DataFrame 的型式的表格。
  2. pd 為 panda 套件的縮寫。
  3. 請以官方文件 panda doc 為主。
  4. 注意panda 的版本(0.25.0),有些功能可能在新版無法使用。


[CH1] Preparing Data

In this chapter, you'll learn about different techniques you can use to import multiple files into DataFrames. Having imported your data into individual DataFrames, you'll then learn how to share information between DataFrames using their Indexes. Understanding how Indexes work is essential information that you'll need for merging DataFrames later in the course.

1. Reading multiple data files

Tools for pandas data import | read_csv()、glob

讀取資料

  • read_csv() 官方文檔
  • pandas 還資源許多其他檔案類型:
    • pd.read_excel()
    • pd.read_html()
    • pd.read_json()

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

使用迴圈

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

使用一句式的for迴圈,批量讀取檔案

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

使用 glob

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

2. Reindexing DataFrames

這邊我們將介紹在pandas裡index的基本操作

“Indexes” vs. “Indices”

  • indices: 在單個index裡的多個標籤
  • indexes: 多個index

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Importing weather data | index、reindex()、sort_index()、dropna()

Pittsburgh weather data (from Datacamp)

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

用print 檢視資料

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

查看index資料

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

重設index

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

將df裡的column 設為index

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

也可以依自己輸入的名字抓取對應的index,當沒有該index回傳NaN

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

以上面reindex後的 w_mean3 的index為準,抓取w_max 對應index的值,並使用drop_na()丟掉空值

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

這邊以 w_meanw_max 抓取互相對應index的值,真方便呢~

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

3.Arithmetic with Series & DataFrames

Loading weather data | loc[ ]

Pittsburgh weather data (from Datacamp)

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

純量的乘法,對指定日期內的PrecipitationIn這個column 乘 2.54

  • df.loc[index_lable,column_lable] 官方文檔
    • 可以抓取指定的index_lable(row名字)和column_lable(col名字)。
    • : 可以抓取一個範圍

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

也可以用list一次選取多欄 ,得到絕對的溫度範圍 week1_range

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

這邊我們先獲取這幾天的平均溫度 week1_mean

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Relative temperature range | divide()、pct_change()

我們想要的到一個相對的比例,但是發生錯誤了QQ

  • 錯誤顯示pandas不知到要怎麼對 timestamp 和 str 做運算,因為她不知道逆要他算dataframe裡面的哪個值

這邊我們使用pandas 內建的divide(),對week1_range 裡的所有儲存格除以 week1_mean

pct_change() 可以產生相對於前一個值得變動比率,因為是相對於前一個值,所以第一個值一定為NaN

Olympic medals data

Summer Olympic medals (from Datacamp)

銅牌獎

銀牌獎

金牌獎

Adding bronze, silver | add()

把兩個資料並一起,可以看到2247分別為bronze和silver的加總

使用add() 也可以,這邊GermanyItaly 因為其中一個df有NaN 所以結果為NaN

我們可以加入 fill_value的參數,只要其中一個友值就填補回來。

Chaining .add()

如果我們想對多個呢?

用多個add串接省去許多麻煩

[CH2] Concatenating data

Having learned how to import multiple DataFrames and share information using Indexes, in this chapter you'll learn how to perform database-style operations to combine DataFrames. In particular, you'll learn about appending and concatenating DataFrames while working with a variety of real-world datasets.

1. Appending & concatenating Series

append 和concat 很類似,兩個都可以用來合併資料

  • append() 官方文檔
    • Series & DataFrame method
    • 用法: s1.append(s2)
    • 只能在s1下面接著s2
  • concat() 官方文檔
    • pandas module function
    • 用法: pd.concat([s1, s2, s3])
    • 可以對row也可以對column

Series of US states data | Series

建立series

append() | reset_index()

使用appemnd後,可以看到資料還保有原本的index

使用reset_index(),重設index

concat()

在concat裡面我們可以直接使用ignore_index 去忽略 原本的index

2. Appending & concatenating DataFrames

Loading population data

一樣,我們先一下它長怎樣

用append將兩個dataframe合併起來,要注意他們兩個的column名稱一樣都是2010 Census Population

Append()

這邊我們換成Populationunemployment 這兩個dataframe

我們將兩個dataframe併起來,但這次就沒那麼順利了,發現許多空值,因為append()預設是以column的名稱為準向後添加。但是這兩筆資料的column名稱不同,所以就自動補上空值。

另外,我們還可以看到這邊有index2860重複了

Concat()

依資料合成的方向主要可以分成兩種

concat rows (axis=0,預設):上下依造row去合併,就是類似上面介紹的append()。

concat columns (axis=1):而這就是左右合併column的意思

  • 注意:NaN的問題,上面兩種方式在合併時,當index沒有對應的值或是兩個dataframe長度不一,concat()會自動幫你填入空值,所以還要再對空值做對應的處理

3 Concatenation, keys, & MultiIndexes

Loading rainfall data | concat(keys=)

先檢視資料長怎樣

對row進行合併

使用keys,我們可以發現它產生了複合index 2013 2014

我們也可以使用loc[ ]去抓取 2014 ,其中還包含月份的index

Concatenating columns

這邊axis='columns'axis=1 是一樣的意思

當然,我們也可以對column使用keys,產生複合的index

pd.concat() with dict

我們也可以對dict,但是格式要注意。

4. Outer & inner joins

Using with arrays | numpy

使用arrays,他是一種在numpy下的資料型態

可以左右併起來

也可以上下併起來

這邊因為array的形狀不對,所以發生錯誤。

Population & unemployment data

把他轉乘array的格式

對應的列數相同,我們可以把它左右併起來

concat(Joins=)

  • 將多個table 的row 合再一起
  • 分肥以下兩種
    • Outer join :取聯集,會補空值NaN
    • Inner join :取交集

inner

outer

再來向下concat 但是因為column之間沒有交集所以為空集合

[CH3] Merging data

Here, you'll learn all about merging pandas DataFrames. You'll explore different techniques for merging, and learn about left joins, right joins, inner joins, and outer joins, as well as when to use which. You'll also learn about ordered merging, which is useful when you want to merge DataFrames whose columns have natural orderings, like date-time columns.

1. Merging DataFrames

Merging

下面我們以人口的資料和城市的資料為例


這邊我們直接使用merge,可以發現他預設的是由右邊的df中index對應的值,合到左邊的df

Merging on multiple columns | merge(on=)

我們跟上面一樣用merge,但是結果卻是空的df,原因是因為兩個df的column 名字都一樣,所以merge不知道你要合哪一個column以甚麼為準。

這邊我們加入 on= 這個參數,可以看到他會以你設定on的那個column為主,去兩個df中對應的值併再一起,因為他們的column一樣,所以merge後會自動加上 _X 、_Y。

也on可以設定兩個columns。

使用 suffixes= 這個變數可以替代轉換後 _X 、_Y 的名字。

Specifying columns to merge

使用left on=right_on,可以設定左右兩個表分別以哪column為基準。

左右反過來也行喔,只是要注意他們對應的參數。

2. Joining DataFrames

merge(how=)

下面合成的方式有四種

inner:兩者交集併再一起

left:以左邊的df為主,把右邊對應的值併過來

right:以右邊的df為主,把左邊對應的值併過來

outer:輛個df的聯集

Using .join()

直接使用join(),他預設是left,就跟merge(how='left')一樣的意思。

join 也一樣可以使用how,這邊我們分別用how=‘right’how=‘outer’how=‘inner’



Which should you use?

append和concat屬於直接合併,而join和merge是依據條件去做兩個資料的串接。其中merge是最客製化的。

  • df1.append(df2): stacking vertically (垂直堆疊)
  • pd.concat([df1, df2]):
    • stacking many horizontally or vertically (垂直和水平堆疊)
    • simple inner/outer joins on Indexes
  • df1.join(df2): inner/outer/left/right joins on Indexes (依據index 作合併)
  • pd.merge([df1, df2]): many joins on multiple columns (可以指定column為依據做合併)

3. Ordered merges

這邊我們使用銷售資料示範一下merge_order()的作用

Using merge_ordered()


首先我們先用merge()

但我們發現sorted_values()沒有用

這時我們可以使用merge_oder(),它會自動按造日期去排。

也可以加入on 和suffixes

Ordered merge with ffill

這邊我們使用股票和GDP資料,示範如何填補合併後ˇ的空值。


我們用merge_oder()將兩個df 依據 Data 合併,但是有些天沒有對應的資料。

於是我們可以使用merge_odered(fill_method=)去填補NaN,而這邊的ffill就是 first fill 的意思,就是依據前一個非空值去填補。