合并數(shù)據(jù)集
數(shù)據(jù)分析和建模方面的大量編程工作都是用在數(shù)據(jù)準備上的:加載、清理、轉(zhuǎn)換以及重塑本冲。有時候厨埋,存放在文件或數(shù)據(jù)庫中的數(shù)據(jù)并不能滿足你的數(shù)據(jù)處理應(yīng)用的要求邪媳。pandas對象中的數(shù)據(jù)可以通過一些內(nèi)置的方式進行合并:
pandas.merge可根據(jù)一個或多個鍵將不同DataFrame中的行連接起來。
數(shù)據(jù)庫風(fēng)格的DataFrame合并
數(shù)據(jù)集的合并(merge)或連接(join)運算是通過一個或多個鍵將行鏈接起來的荡陷。這些運算是關(guān)系型數(shù)據(jù)庫的核心雨效。pandas的merge函數(shù)是對數(shù)據(jù)應(yīng)用這些算法的主要切入點。
In [1]: from pandas import Series,DataFrame
In [2]: import pandas as pd
In [3]: import numpy as np
In [6]: df1=DataFrame({'key':['b', 'b', 'a', 'c', 'a', 'a', 'b'],
...: 'data1':range(7)})
In [7]: df2=DataFrame({'key': ['a', 'b', 'd'],'data2':range(3)})
In [8]: df1
Out[8]:
data1 key
0 0 b
1 1 b
2 2 a
3 3 c
4 4 a
5 5 a
6 6 b
In [9]: df2
Out[9]:
data2 key
0 0 a
1 1 b
2 2 d
這是一種多對一的合并废赞。df1中的數(shù)據(jù)有多個被標記為a和b的行设易,而df2中key列的每個值則僅對應(yīng)一行。對這些對象調(diào)用merge即可得到
In [10]: pd.merge(df1,df2)
Out[10]:
data1 key data2
0 0 b 1
1 1 b 1
2 6 b 1
3 2 a 0
4 4 a 0
5 5 a 0
并沒有指明要用哪個列進行連接蛹头。如果沒有指定顿肺,merge就會將重疊列的列名當做鍵。不過渣蜗,最好顯式指定一下
In [11]: pd.merge(df1, df2, on='key')
Out[11]:
data1 key data2
0 0 b 1
1 1 b 1
2 6 b 1
3 2 a 0
4 4 a 0
5 5 a 0
如果兩個對象的列名不同屠尊,也可以分別進行指定
In [12]: df3 = DataFrame({'lkey': ['b', 'b', 'a', 'c', 'a', 'a', 'b'],
...: 'data1': range(7)})
In [13]: df4 = DataFrame({'rkey': ['a', 'b', 'd'],
...: 'data2': range(3)})
In [14]: df3
Out[14]:
data1 lkey
0 0 b
1 1 b
2 2 a
3 3 c
4 4 a
5 5 a
6 6 b
In [15]: df4
Out[15]:
data2 rkey
0 0 a
1 1 b
2 2 d
In [16]: pd.merge(df3, df4, left_on='lkey', right_on='rkey')
Out[16]:
data1 lkey data2 rkey
0 0 b 1 b
1 1 b 1 b
2 6 b 1 b
3 2 a 0 a
4 4 a 0 a
5 5 a 0 a
已經(jīng)注意到了,結(jié)果里面c和d以及與之相關(guān)的數(shù)據(jù)消失了耕拷。默認情況下讼昆,merge做的是"inner"連接;結(jié)果中的鍵是交集骚烧。其他方式還有"left"浸赫、"right"以及"outer"闰围。外連接求取的是鍵的并集,組合了左連接和右連接的效果
In [17]: pd.merge(df1, df2, how='outer')
Out[17]:
data1 key data2
0 0.0 b 1.0
1 1.0 b 1.0
2 6.0 b 1.0
3 2.0 a 0.0
4 4.0 a 0.0
5 5.0 a 0.0
6 3.0 c NaN
7 NaN d 2.0
多對多的合并操作比較簡單既峡,如下所示
In [18]: df1 = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'b'],
...: 'data1': range(6)})
In [19]: df2 = DataFrame({'key': ['a', 'b', 'a', 'b', 'd'],
...: 'data2': range(5)})
In [20]: df1
Out[20]:
data1 key
0 0 b
1 1 b
2 2 a
3 3 c
4 4 a
5 5 b
In [21]: df2
Out[21]:
data2 key
0 0 a
1 1 b
2 2 a
3 3 b
4 4 d
In [22]: pd.merge(df1, df2, on='key', how='left')
Out[22]:
data1 key data2
0 0 b 1.0
1 0 b 3.0
2 1 b 1.0
3 1 b 3.0
4 2 a 0.0
5 2 a 2.0
6 3 c NaN
7 4 a 0.0
8 4 a 2.0
9 5 b 1.0
10 5 b 3.0
多對多連接產(chǎn)生的是行的笛卡爾積羡榴。由于左邊的DataFrame有3個"b"行,右邊的有2個运敢,所以最終結(jié)果中就有6個"b"行校仑。連接方式只影響出現(xiàn)在結(jié)果中的鍵
In [23]: pd.merge(df1, df2, how='inner')
Out[23]:
data1 key data2
0 0 b 1
1 0 b 3
2 1 b 1
3 1 b 3
4 5 b 1
5 5 b 3
6 2 a 0
7 2 a 2
8 4 a 0
9 4 a 2
In [24]: left = DataFrame({'key1': ['foo', 'foo', 'bar'],
...: 'key2': ['one', 'two', 'one'],
...: 'lval': [1, 2, 3]})
要根據(jù)多個鍵進行合并,傳入一個由列名組成的列表即可
In [25]: right = DataFrame({'key1': ['foo', 'foo', 'bar', 'bar'],
...: 'key2': ['one', 'one', 'one', 'two'],
...: 'rval': [4, 5, 6, 7]})
In [26]: left
Out[26]:
key1 key2 lval
0 foo one 1
1 foo two 2
2 bar one 3
In [27]: right
Out[27]:
key1 key2 rval
0 foo one 4
1 foo one 5
2 bar one 6
3 bar two 7
In [28]: pd.merge(left, right, on=['key1', 'key2'], how='outer')
Out[28]:
key1 key2 lval rval
0 foo one 1.0 4.0
1 foo one 1.0 5.0
2 foo two 2.0 NaN
3 bar one 3.0 6.0
4 bar two NaN 7.0
警告: 在進行列-列連接時传惠,DataFrame對象中的索引會被丟棄迄沫。
對于合并運算需要考慮的最后一個問題是對重復(fù)列名的處理。雖然你可以手工處理列名重疊的問題(稍后將會介紹如何重命名軸標簽)卦方,但merge有一個更實用的suffixes選項羊瘩,用于指定附加到左右兩個DataFrame對象的重疊列名上的字符串
In [29]: pd.merge(left, right, on='key1')
Out[29]:
key1 key2_x lval key2_y rval
0 foo one 1 one 4
1 foo one 1 one 5
2 foo two 2 one 4
3 foo two 2 one 5
4 bar one 3 one 6
5 bar one 3 two 7
In [30]: pd.merge(left, right, on='key1', suffixes=('_left', '_right'))
Out[30]:
key1 key2_left lval key2_right rval
0 foo one 1 one 4
1 foo one 1 one 5
2 foo two 2 one 4
3 foo two 2 one 5
4 bar one 3 one 6
5 bar one 3 two 7
merge的參數(shù)請參見表7-1
索引上的合并
有時候,DataFrame中的連接鍵位于其索引中盼砍。在這種情況下尘吗,你可以傳入left_index=True或right_index=True(或兩個都傳)以說明索引應(yīng)該被用作連接鍵
In [4]: left1 = DataFrame({'key': ['a', 'b', 'a', 'a', 'b', 'c'],
...: 'value': range(6)})
In [5]: left1
Out[5]:
key value
0 a 0
1 b 1
2 a 2
3 a 3
4 b 4
5 c 5
In [6]: right1 = DataFrame({'group_val': [3.5, 7]}, index=['a', 'b'])
In [7]: right1
Out[7]:
group_val
a 3.5
b 7.0
In [8]: pd.merge(left1, right1, left_on='key', right_index=True)
Out[8]:
key value group_val
0 a 0 3.5
2 a 2 3.5
3 a 3 3.5
1 b 1 7.0
4 b 4 7.0
由于默認的merge方法是求取連接鍵的交集,因此你可以通過外連接的方式得到它們的并集
In [9]: pd.merge(left1, right1, left_on='key', right_index=True, how='outer')
Out[9]:
key value group_val
0 a 0 3.5
2 a 2 3.5
3 a 3 3.5
1 b 1 7.0
4 b 4 7.0
5 c 5 NaN
對于層次化索引的數(shù)據(jù)衬廷,事情就有點復(fù)雜
In [10]: lefth = DataFrame({'key1': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
...: 'key2': [2000, 2001, 2002, 2001, 2002],
...: 'data': np.arange(5)})
In [11]: righth = DataFrame(np.arange(12).reshape((6, 2)),
...: index=[['Nevada', 'Nevada', 'Ohio', 'Ohio', 'Ohio', 'Ohio'],
...: [2001, 2000, 2000, 2000, 2001, 2002]],
...: columns=['event1', 'event2'])
In [12]: lefth
Out[12]:
data key1 key2
0 0 Ohio 2000
1 1 Ohio 2001
2 2 Ohio 2002
3 3 Nevada 2001
4 4 Nevada 2002
In [13]: righth
Out[13]:
event1 event2
Nevada 2001 0 1
2000 2 3
Ohio 2000 4 5
2000 6 7
2001 8 9
2002 10 11
對于層次索引摇予,以列表的形式指明用作合并鍵的多個列(注意對重復(fù)索引值的處理)
In [14]: pd.merge(lefth, righth, left_on=['key1', 'key2'], right_index=True)
Out[14]:
data key1 key2 event1 event2
0 0 Ohio 2000 4 5
0 0 Ohio 2000 6 7
1 1 Ohio 2001 8 9
2 2 Ohio 2002 10 11
3 3 Nevada 2001 0 1
In [15]: pd.merge(lefth, righth, left_on=['key1', 'key2'],
...: right_index=True, how='outer')
Out[15]:
data key1 key2 event1 event2
0 0.0 Ohio 2000 4.0 5.0
0 0.0 Ohio 2000 6.0 7.0
1 1.0 Ohio 2001 8.0 9.0
2 2.0 Ohio 2002 10.0 11.0
3 3.0 Nevada 2001 0.0 1.0
4 4.0 Nevada 2002 NaN NaN
4 NaN Nevada 2000 2.0 3.0
同時使用合并雙方的索引也沒問題
In [16]: left2 = DataFrame([[1, 2], [3, 4], [5, 6]], index=['a', 'c', 'e'],
...: columns=['Ohio', 'Nevada'])
In [17]: right2 = DataFrame([[7, 8], [9, 10], [11, 12], [13, 14]],
...: index=['b', 'c', 'd', 'e'], columns=['Missouri', 'Alabama'])
In [18]: left2
Out[18]:
Ohio Nevada
a 1.0 2.0
c 3.0 4.0
e 5.0 6.0
In [19]: right2
Out[19]:
Missouri Alabama
b 7.0 8.0
c 9.0 10.0
d 11.0 12.0
e 13.0 14.0
In [20]: pd.merge(left2, right2, how='outer', left_index=True, right_index=True)
Out[20]:
Ohio Nevada Missouri Alabama
a 1.0 2.0 NaN NaN
b NaN NaN 7.0 8.0
c 3.0 4.0 9.0 10.0
d NaN NaN 11.0 12.0
e 5.0 6.0 13.0 14.0
DataFrame還有一個join實例方法,它能更為方便地實現(xiàn)按索引合并吗跋。它還可用于合并多個帶有相同或相似索引的DataFrame對象侧戴,而不管它們之間有沒有重疊的列。
In [21]: left2.join(right2, how='outer')
Out[21]:
Ohio Nevada Missouri Alabama
a 1.0 2.0 NaN NaN
b NaN NaN 7.0 8.0
c 3.0 4.0 9.0 10.0
d NaN NaN 11.0 12.0
e 5.0 6.0 13.0 14.0
由于一些歷史原因(早期版本的pandas)跌宛,DataFrame的join方法是在連接鍵上做左連接酗宋。它還支持參數(shù)DataFrame的索引跟調(diào)用者DataFrame的某個列之間的連接
In [22]: left1.join(right1, on='key')
Out[22]:
key value group_val
0 a 0 3.5
1 b 1 7.0
2 a 2 3.5
3 a 3 3.5
4 b 4 7.0
5 c 5 NaN
對于簡單的索引合并,你還可以向join傳入一組DataFrame(后面我們會介紹更為通用的concat函數(shù)疆拘,它也能實現(xiàn)此功能)
In [23]: another = DataFrame([[7., 8], [9, 10], [11, 12], [16, 17]],
...: index=['a', 'c', 'e', 'f'], columns=['New York', 'Oregon'])
In [24]: left2.join([right2, another])
Out[24]:
Ohio Nevada Missouri Alabama New York Oregon
a 1.0 2.0 NaN NaN 7.0 8.0
c 3.0 4.0 9.0 10.0 9.0 10.0
e 5.0 6.0 13.0 14.0 11.0 12.0
In [25]: left2.join([right2, another], how='outer')
Out[25]:
Ohio Nevada Missouri Alabama New York Oregon
a 1.0 2.0 NaN NaN 7.0 8.0
b NaN NaN 7.0 8.0 NaN NaN
c 3.0 4.0 9.0 10.0 9.0 10.0
d NaN NaN 11.0 12.0 NaN NaN
e 5.0 6.0 13.0 14.0 11.0 12.0
f NaN NaN NaN NaN 16.0 17.0
接下來練習(xí)軸向連接和數(shù)據(jù)轉(zhuǎn)換蜕猫。