李宗棠
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Combining Datasets: Concat and Append > Lee Tsung-Tang > ###### tags: `python` `pandas` `combining data` `Python Data Science Handbook` 引用整理自[Python Data Science Handbook CH3](https://jakevdp.github.io/PythonDataScienceHandbook/) [TOC] {%hackmd @88u1wNUtQpyVz9FsQYeBRg/r1vSYkogS %} pnadas有多種不同合併資料的方式,從簡單到複雜的操作 > Here we'll take a look at simple concatenation of Series and DataFrames with the `pd.concat` function; later we'll dive into more sophisticated in-memory `merges` and `joins` implemented in Pandas. ```python= import pandas as pd import numpy as np # useful way to make dataframe def make_df(cols, ind): """Quickly make a DataFrame""" data = {c: [str(c) + str(i) for i in ind] for c in cols} return pd.DataFrame(data, ind) # example DataFrame make_df('ABC', range(3)) # A B C #0 A0 B0 C0 #1 A1 B1 C1 #2 A2 B2 C2 ``` In addition, we'll create a quick class that allows us to display multiple `DataFrames` side by side. The code makes use of the special `_repr_html_` method, which IPython uses to implement its rich object display: ```python= class display(object): """Display HTML representation of multiple objects""" template = """<div style="float: left; padding: 10px;"> <p style='font-family:"Courier New", Courier, monospace'>{0}</p>{1} </div>""" def __init__(self, *args): self.args = args def _repr_html_(self): return '\n'.join(self.template.format(a, eval(a)._repr_html_()) for a in self.args) def __repr__(self): return '\n\n'.join(a + '\n' + repr(eval(a)) for a in self.args) ``` ## Recall: Concatenation of NumPy Arrays 參考[The Basics of NumPy Arrays](/cNcuLIl_QoWF4_Gz494HrQ) > Concatenation of `Series` and `DataFrame` objects is very similar to concatenation of Numpy `arrays` (`np.concatenate()`) 範例如下 ```python= x = [1, 2, 3] y = [4, 5, 6] z = [7, 8, 9] np.concatenate([x, y, z]) array([1, 2, 3, 4, 5, 6, 7, 8, 9]) ``` > `np.concatenate()`的第一個arg. 是`tuple`或`list` of `arrays`; 第二個arg. `axis`是合併的方向 > ```python= x = [[1, 2], [3, 4]] np.concatenate([x, x], axis=1) # by row array([[1, 2, 1, 2], [3, 4, 3, 4]]) ``` ## Simple Concatenation with `pd.concat` pandas 的 `pd.concat()`與numpy的類似,但有更多的參數可以調整 ```python= # Signature in Pandas v0.18 pd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, copy=True) ``` > 簡單的合併 `series` `DataFrame` ```python= ser1 = pd.Series(['A', 'B', 'C'], index=[1, 2, 3]) ser2 = pd.Series(['D', 'E', 'F'], index=[4, 5, 6]) pd.concat([ser1, ser2]) #1 A #2 B #3 C #4 D #5 E #6 F #dtype: object ``` > `DataFrame` > ```python= df1 = make_df('AB', [1, 2]) df2 = make_df('AB', [3, 4]) display('df1', 'df2', 'pd.concat([df1, df2])') ``` ![](https://i.imgur.com/QRLX6vz.png) :a: `pd.concat()`預設是以列合併(row-wise) > `pd.concat()`同樣也能用`axis`參數控制合併的方向 ```python= df3 = make_df('AB', [0, 1]) df4 = make_df('CD', [0, 1]) display('df3', 'df4', "pd.concat([df3, df4], axis='col')") ``` ![](https://i.imgur.com/3RhSueX.png) :a: `axis='col'`等價於`axis=1`;`axis='row'`等價於`axis=0` (用0、1容易混淆) ## Duplicate indices > `pd.concat`與`np.concatenate`最大的不同是pandas版本的在合併時即使會有**重複**的index發生也會==全部保留== ```python= x = make_df('AB', [0, 1]) y = make_df('AB', [2, 3]) y.index = x.index # make duplicate indices! display('x', 'y', 'pd.concat([x, y])') ``` ![](https://i.imgur.com/5Wmxege.png) :a: 重複的index在`DataFrame`會造成許多額外的問題,`pd.concat()`提供幾種方式處理 #### Catching the repeats as an error > 設定`verify_integrity` argument 為`True`,此時如果遇到重複的index就會有error ```python= try: pd.concat([x, y], verify_integrity=True) except ValueError as e: print("ValueError:", e) #ValueError: Indexes have overlapping values: [0, 1] ``` #### Ignoring the index > 忽略原本的index,直接給新一組index > `ignore_index=True` ```python= display('x', 'y', 'pd.concat([x, y], ignore_index=True)') ``` ![](https://i.imgur.com/lI0Gmu5.png) #### Adding MultiIndex keys > 使用hierarchically indexed > `keys` ```python= display('x', 'y', "pd.concat([x, y], keys=['x', 'y'])") ``` ![](https://i.imgur.com/OgLpwx2.png) :a: 可以用[Hierarchical Indexing](/fX8rYDVrQLOTN2Q5QvOmzA)討論的方法進行操作 ### Concatenation with joins > 如果`DataFrame`欄位不一致,`pd.concate()`有幾種方式可以處理 ```python= df5 = make_df('ABC', [1, 2]) df6 = make_df('BCD', [3, 4]) display('df5', 'df6', 'pd.concat([df5, df6])') ``` ![](https://i.imgur.com/g0EabHZ.png) :a: 預設是保留所有欄位,如果的`DataFrame`在對應的欄位沒有資料就會是遺漏值(`NaN`) > `join_axes` `join` 可以控制合併的方式,預設的聯集合併方式為`join='outer'`,也可以調整為交集合併`join='inner'` ```python= display('df5', 'df6', "pd.concat([df5, df6], join='inner')") ``` ![](https://i.imgur.com/RMs301J.png) :a: 合併後的資料只保留兩邊都有的欄位 > 另一個方法是用`join_axes`直接放入要保留的list of index objects > 下例是放入其中一個`DataFrame`的columns,表示合併後的資料只保留這些columns ```python= display('df5', 'df6', "pd.concat([df5, df6], join_axes=[df5.columns])") ``` ![](https://i.imgur.com/RbiMysl.png) #### Concatenation mulitiple DataFrame(補充) 這邊是其他補充資料 > 可以直接input `list` of `DataFrame`合併多個資料 > ```python= pdList = [df1, df2, ...] # List of your dataframes new_df = pd.concat(pdList) ``` ### The append() method > `pd.concat([df1, df2])`等價於`df1.append(df2)` ```python= display('df1', 'df2', 'df1.append(df2)') ``` ![](https://i.imgur.com/386mLU7.png) :warning: 與`list`的`append()`、`extend()`不同,pandas的`append()`不會直接改變原本的資料,而是create新的object。這會額外消耗大量記憶體,所以如果要合併大量資料,建議使用`pd.concat()`

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully