note.nkmk.me

pandas.DataFrameの連結

Date: 2015-07-29 / tags: Python, pandas
このエントリーをはてなブックマークに追加

pandas.concatを使う。

連結方向はaxisで設定。デフォルトは縦方向axis=0

join='outer'(デフォルト)にすると和集合、join='inner'にすると共通部分のDataFrameを返す。

import pandas as pd

df1 = pd.DataFrame({'A': [11, 21, 31],
                    'B': [12, 22, 32],
                    'C': [13, 23, 33]},
                   index=['ONE', 'TWO', 'THREE'])

df2 = pd.DataFrame({'C': [11, 21, 31],
                    'D': [12, 22, 32]},
                   index=['TWO', 'THREE', 'FOUR'])

df_v = pd.concat([df1, df2], axis=0)
print df_v
#         A   B   C   D
# ONE    11  12  13 NaN
# TWO    21  22  23 NaN
# THREE  31  32  33 NaN
# TWO   NaN NaN  11  12
# THREE NaN NaN  21  22
# FOUR  NaN NaN  31  32

df_v_in = pd.concat([df1, df2], axis=0, join='inner')
print df_v_in
#         C
# ONE    13
# TWO    23
# THREE  33
# TWO    11
# THREE  21
# FOUR   31

df_h = pd.concat([df1, df2], axis=1)
print df_h
#         A   B   C   C   D
# FOUR  NaN NaN NaN  31  32
# ONE    11  12  13 NaN NaN
# THREE  31  32  33  21  22
# TWO    21  22  23  11  12

df_h_in = pd.concat([df1, df2], axis=1, join='inner')
print df_h_in
#         A   B   C   C   D
# TWO    21  22  23  11  12
# THREE  31  32  33  21  22

参考

スポンサーリンク
シェア
このエントリーをはてなブックマークに追加

関連カテゴリー

関連記事