超詳細教程 | pandas合併之append和concat

pandas

​ 本篇文章主要介紹了pandas中對series和dataframe對象進行連接的方法:pd.append()和pd.concat(),文中通過示例代碼對這兩種方法進行了詳細的介紹,希望能對各位python小白的學習有所幫助。

一、df.append(df)

描述:append方法用以在表尾中添加新的行,並返回追加後的數據對象,若追加的行中存在原數據沒有的列,會新增一列,並用nan填充;若追加的行數據中缺少原數據某列,同樣以nan填充

語法:df.append(other, ignore_index=False, verify_integrity=False, sort=None)

​ 參數說明:

  • other:要追加的數據,可以是dataframe,series,字典,列表
  • ignore_index:兩個表的index是否有實際含義,默認爲False,若ignore_index=True,表根據列名對齊合併,生成新的index
  • verify_integrity:默認爲False,若爲True,創建具有重複項的索引時引發ValueError
  • sort:默認爲False,若爲True如果’ self ‘和’ other '的列沒有對齊,則對列進行排序。

下面對append方法的每個參數進行詳細介紹:

​ 第一個參數爲other:要追加的數據,可以是dataframe,series,字典,列表甚至是元素;但前後類型要一致。

  1. 將數據追加到series
# 將數據追加到series
<<< a=df.iloc[0,:]
<<< b=df.iloc[6,:]
<<< a.append(b)      #需賦給新值,不改變原數組
A     0
B     1
C     2
D     3
E     4
F     5
A    36
B    37
C    38
D    39
E    40
F    41
dtype: int32
<<< a
A    0
B    1
C    2
D    3
E    4
F    5
Name: S1, dtype: int32

<<< c=a.append(b)    # 保存爲c
<<< c
A     0
B     1
C     2
D     3
E     4
F     5
A    36
B    37
C    38
D    39
E    40
F    41
dtype: int32
  1. 將數據追加到dataframe
# 將數據追加到dataframe
<<< a=df.iloc[0:2,:]
<<< b=df.iloc[4:6,:] 
<<< c=a.append(b)           # 注意是縱向追加,不支持橫向追加
<<< c
    A	B	C	D	E   F
S1	0	1	2	3	4	5
S2	6	7	8	9	10	11
S5	24	25	26	27	28	29
S6	30	31	32	33	34	35

​ 注意:獲取單行得到的結果是一維數組,當一維數組[6,:]和二維數組[2,6]追加時,會得到8*7的數組,匹配不上的地方用NA填充。

# 將二維數組追加到一維數組
<<< a=df.iloc[0,:]
<<< b=df.iloc[4:6,:] 
<<< c=a.append(b)          
<<< c
      0	  A	  B	  C	  D	  E	  F
A	0.0	NaN	NaN	NaN	NaN	NaN	NaN
B	1.0	NaN	NaN	NaN	NaN	NaN	NaN
C	2.0	NaN	NaN	NaN	NaN	NaN	NaN
D	3.0	NaN	NaN	NaN	NaN	NaN	NaN
E	4.0	NaN	NaN	NaN	NaN	NaN	NaN
F	5.0	NaN	NaN	NaN	NaN	NaN	NaN
S5	NaN	24.0	25.0	26.0	27.0	28.0	29.0
S6	NaN	30.0	31.0	32.0	33.0	34.0	35.0
  1. 將數據追加到list
  • list是一維:以列的形式來進行追加操作

  • list是二維:以行的形式來進行追加操作

  • list是三維:只添加一個值

    注意:追加到列表時,是在原數組改動,是在原數組改動,是在原數組改動

# 列表追加到列表
<<< a=[]
<<< b=df.iloc[6,:].tolist()
<<< a.append(b)
<<< a
[[36, 37, 38, 39, 40, 41]]

# 序列追加到列表
<<< a=[1,2,3,4,5,6,7]
<<< b=df.iloc[6,:]
<<< a.append(b)
<<< a
[1, 2, 3, 4, 5, 6, 7, A    36
 B    37
 C    38
 D    39
 E    40
 F    41
 Name: S7, dtype: int32]
  1. 追加字典

    TypeError: Can only append a Series if ignore_index=True or if the Series has a name

<<< df1=pd.DataFrame()
<<< a={'A':1,'B':2}
<<< df1=df1.append(a,ignore_index=True)
<<< df1
    A	B
0	1	2
  1. 將單個元素追加到列表

​ append方法也可以將單個元素追加到列表(其他對象不行),會自動將單個元素轉爲列表對象,再進行追加操作

# 單個元素進行追加
<<< a=[1,2,3,4,5,6,7,8]
<<< a.append(9)
<<< a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
  1. 將其他類型對象追加到dataframe

    當dataframe使用append方法添加series或字典的時候,必須要設置name,設置name名稱將會作爲index的name,否則會報錯提示:TypeError: Can only append a Series if ignore_index=True or if the Series has a name

<<< df1=pd.DataFrame()
<<< ser=pd.Series({"x":1,"y":2},name="a")
<<< df1=df1.append(ser)
<<< df1
    x   y
a	1	2

​ 如果不添加name,也可以添加參數ignore_index

<<< df1=pd.DataFrame()
<<< ser=pd.Series({"x":1,"y":2})
<<< df1=df1.append(ser,ignore_index=True)
<<< df1
    x   y
a	1	2

​ 第二個參數:兩個表的index是否有實際含義,默認ignore_index=False,若爲True,表根據列名對齊合併,生成新的index。

<<< a=df.iloc[0:2,:]
<<< b=df.iloc[4:6,:]
<<< a.append(b,ignore_index=True)  
    A   B	C   D   E   F
0	0	1	2	3	4	5
1	6	7	8	9	10	11
2	24	25	26	27	28	29
3	30	31	32	33	34	35

<<< a=df.iloc[0:2,:]
<<< b=df.iloc[4:6,:]
<<< a.append(b)
    A	B	C	D	E   F
S1	0	1	2	3	4	5
S2	6	7	8	9	10	11
S5	24	25	26	27	28	29
S6	30	31	32	33	34	35

​ 在dataframe中,使用append方法進行表合併時,二者匹配不上的地方用NAN填充。

<<< df1=df.copy()
<<< df2=pd.DataFrame(np.arange(8).reshape(2,4),columns=<<<['s1','s2','s3','s4'])
<<< df_new=df1.append(df2,ignore_index=True)
<<< df_new
    A	B	C	D	E	F	S1	S2	s3	s4
0	0	1	2	3	4	5	NaN	NaN	NaN	NaN
1	6	7	8	9	10	11	NaN	NaN	NaN	NaN
2	12	13	14	15	16	17	NaN	NaN	NaN	NaN
3	18	19	20	21	22	23	NaN	NaN	NaN	NaN
4	24	25	26	27	28	29	NaN	NaN	NaN	NaN
5	30	31	32	33	34	35	NaN	NaN	NaN	NaN
6	36	37	38	39	40	41	NaN	NaN	NaN	NaN
7	NaN	NaN	NaN	NaN	NaN	NaN	0	1	2	3
8	NaN	NaN	NaN	NaN	NaN	NaN	4	5	6	7

​ 第三個參數爲verify_integrity:默認爲False 參數用於檢查結果對象新連接軸上的索引是否有重複項,有的話引發 ValueError,可以看到這個參數的作用與ignore_index 是互斥的。 (如果 ignore_index = True ,則意味着index不能是重複的,而ignore_index = False ,則意味着index可以是重複的)

<<< df1=df.copy()
<<< df2=pd.DataFrame(np.arange(8).reshape(2,4),columns=   <<< ['G','H','I','J'],index=['S1','S8'],dtype=int)
<<< pd.set_option('precision',0)
<<< df_new=df1.append(df2,verify_integrity=False)
<<< df_new
    A	B	C	D	E	F	G	H	I	J
S1	0	1	2	3	4	5	NaN	NaN	NaN	NaN
S2	6	7	8	9	10	11	NaN	NaN	NaN	NaN
S3	12	13	14	15	16	17	NaN	NaN	NaN	NaN
S4	18	19	20	21	22	23	NaN	NaN	NaN	NaN
S5	24	25	26	27	28	29	NaN	NaN	NaN	NaN
S6	30	31	32	33	34	35	NaN	NaN	NaN	NaN
S7	36	37	38	39	40	41	NaN	NaN	NaN	NaN
S1	NaN	NaN	NaN	NaN	NaN	NaN	0	1	2	3
S8	NaN	NaN	NaN	NaN	NaN	NaN	4	5	6	7

注意:當需要連接的兩個表的index有重複值時,設置ignore_index = True則會報錯。

​ 第四個參數爲sort:默認是False,該屬性在pandas的0.23.0版本纔有,若爲True,則對兩個表沒匹配上的列名,進行排序,若爲False,不排序。

<<< df1=pd.DataFrame(np.arange(8).reshape(2,4),columns=   <<< ['A1','B1','C1','D1'],index=['S1','S2'])
<<< df2=pd.DataFrame(np.arange(8).reshape(2,4),columns=   <<< ['A2','B2','C2','D2'],index=['S1','S3'])
<<< pd.set_option('precision',0)
<<< df_new=df1.append(df2,sort=True)
<<< df_new
    A1	A2	B1	B2	C1	C2	D1	D2
S1	0	NaN	1	NaN	2	NaN	3	NaN
S2	4	NaN	5	NaN	6	NaN	7	NaN
S1	NaN	0	NaN	1	NaN	2	NaN	3
S3	NaN	4	NaN	5	NaN	6	NaN	7

二、pd.concat([df_01,df_02])

描述:concat方法用以將兩個或多個pandas對象根據軸(橫向/縱向)進行拼接,concat函數是在pandas命名空間下的方法,因此需要通過pd.concat()的方式來引用。

語法:pd.concat(‘objs’, ‘axis=0’, “join=‘outer’”, ‘join_axes=None’, ‘ignore_index=False’, ‘keys=None’, ‘levels=None’, ‘names=None’, ‘verify_integrity=False’, ‘sort=None’, ‘copy=True’)

常用參數:

  • objs:要進行拼接的pandas對象,可用中括號[]將兩個或多個對象括起來
  • axis:指定對象按照那個軸進行拼接,默認爲0(縱向拼接),1爲橫向橫向拼接
  • join:拼接的方式,inner爲交集,outer爲並集
  • join_axes:index的列表,僅在橫向合併時使用,指明要將數據合併入哪個原表的index。
  • ignore_index:默認爲False,如果設置爲true,則無視表原來的軸標籤,直接合並,合併後生成新的軸標籤。
  • keys:表標識的列表,用來區分合並的表來自哪裏。

下面,將對concat方法以上各個參數進行詳細說明:

​ 第一個要學習的參數爲objs:要進行拼接的pandas對象,可用中括號[]將兩個或多個對象括起來。

1)對series進行拼接

<<< ser1=pd.Series(np.arange(9))
<<< ser2=pd.Series(np.arange(9))
# 對兩個series對象進行拼接
<<< pd.concat([ser1,ser2])
0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
dtype: int32
  1. 對DataFrame進行拼接
<<< df1=pd.DataFrame(np.arange(9).reshape(3,3),columns=   <<< ['A','B','C'],index=['a','b','c'])
<<< df2=pd.DataFrame(np.arange(9).reshape(3,3),columns=   <<< ['D','E','F'],index=['e','f','g'])
# 對兩個DataFrame對象進行拼接
<<< pd.concat([df1,df2])
    A   B	C	D	E   F
a	0	1	2	NaN	NaN	NaN
b	3	4	5	NaN	NaN	NaN
c	6	7	8	NaN	NaN	NaN
e	NaN	NaN	NaN	0	1	2
f	NaN	NaN	NaN	3	4	5
g	NaN	NaN	NaN	6	7	8

​ 第二個要學習的參數爲axis:指定對象按照那個軸進行拼接,默認爲0(縱向拼接),1爲橫向橫向拼接。

<<< df1=pd.DataFrame(np.arange(9).reshape(3,3),columns=   <<< ['A','B','C'],index=['a','b','c'])
<<< df2=pd.DataFrame(np.arange(9).reshape(3,3),columns=   <<< ['D','E','F'],index=['a','b','d'])
# 將數據對象df1和df2沿1軸進行拼接,即進行橫向拼接
<<< pd.concat([df1,df2],axis=1)
    A	B	C	D	E	F
a	0	1	2	0	1	2
b	3	4	5	3	4	5
c	6	7	8	NaN	NaN	NaN
d	NaN	NaN	NaN	6	7	8

​ 注意:當對Series進行拼接時,設置axis=0進行縱向拼接的結果對象爲Series,設置axis=1進行橫向拼接的結果對象爲DataFrame。

<<< ser1=pd.Series(np.arange(9))
<<< ser2=pd.Series(np.arange(9))
# 對Series進行拼接縱向拼接,結果認爲Series對象
<<< a=pd.concat([ser1,ser2],axis=0)
<<< type(a)
pandas.core.series.Series
# 對Series進行拼接橫向拼接,結果轉換爲DataFrame對象
<<< b=pd.concat([ser1,ser2],axis=1)
<<< type(b)
pandas.core.frame.DataFrame

​ 第三個要學習的參數爲join:拼接的方式,inner爲交集,outer爲並集,橫向拼接時由index的交/並集決定,縱向拼接時由columns的交/並集決定,同時,如果join=outer,匹配不上的地方以nan填充。

<<< df1=pd.DataFrame(np.arange(9).reshape(3,3),columns=   <<< ['A','B','C'],index=['a','b','c'])
<<< df2=pd.DataFrame(np.arange(9).reshape(3,3),columns=   <<< ['D','E','F'],index=['a','b','d'])
# 將df1和df2進行橫向合併,取二者的並集
<<< pd.concat([df1,df2],axis=1)
    A	B	C	D	E	F
a	0	1	2	0	1	2
b	3	4	5	3	4	5
c	6	7	8	NaN	NaN	NaN
d	NaN	NaN	NaN	6	7	8
# 將df1和df2進行橫向合併,只取二者的交集
<<< pd.concat([df1,df2],axis=1,join='inner')
    A	B	C	D	E	F
a	0	1	2	0	1	2
b	3	4	5	3	4	5

​ 第四個要學習的參數爲join_axes:以哪個數據對象的index/columns作爲軸進行拼接,當進行橫向拼接時,join_axes爲index的列表,如需根據df1對齊數據,則會保留df1的index,再將df2的數據進行拼接;同理,縱向拼接時爲columns的列表。

<<< df1=pd.DataFrame(np.arange(9).reshape(3,3),columns=   <<< ['A','B','C'],index=['a','b','c'])
<<< df2=pd.DataFrame(np.arange(9).reshape(3,3),columns=   <<< ['D','E','F'],index=['a','b','d'])
# 根據df1的index對齊數據
<<< pd.concat([df1,df2],axis=1,join_axes=[df1.index])
    A	B	C	D	E	F
a	0	1	2	0	1	2
b	3	4	5	3	4	5
c	6	7	8	NaN	NaN	NaN
# 根據df2的index對齊數據
<<< pd.concat([df1,df2],axis=1,join_axes=[df2.index])
    A	B	C	D	E	F
a	0	1	2	0	1	2
b	3	4	5	3	4	5
d	NaN	NaN	NaN	6	7	8

​ 第五個要學習的參數爲ignore_index:默認爲False,如果設置爲true,則無視表原來的軸標籤,直接合並,合併後生成新的軸標籤。

​ 這裏需要注意的是,與append方法只能進行縱向拼接不同,concat方法既可以進行橫向拼接,也可以進行縱向拼接,若設置ignore_index=True,當進行橫向拼接時,則無視原表的columns,直接合並,合併後生成默認的columns;同理,當進行縱向拼接時,則是忽略原表的index,生成新的index。

<<< df1=pd.DataFrame(np.arange(9).reshape(3,3),columns=   <<< ['A','B','C'],index=['a','b','c'])
<<< df2=pd.DataFrame(np.arange(9).reshape(3,3),columns=   <<< ['D','E','F'],index=['a','b','d'])
# 橫向拼接時,忽略的是columns,index仍起作用
<<< pd.concat([df1,df2],axis=1,ignore_index=True)
    0	1	2	3	4	5
a	0	1	2	0	1	2
b	3	4	5	3	4	5
c	6	7	8	NaN	NaN	NaN
d	NaN	NaN	NaN	6	7	8
# 縱向拼接時,忽略的是index,columns仍起作用
pd.concat([df1,df2],axis=0,ignore_index=True)
    0	1	2	3	4	5
a	0	1	2	0	1	2
b	3	4	5	3	4	5
c	6	7	8	NaN	NaN	NaN
d	NaN	NaN	NaN	6	7	8

​ 第六個要學習的參數爲keys:表標識的列表,用來區分合並後的數據來源於哪個表,當ignore_index=True時,此參數的作用失效。

<<< df1=pd.DataFrame(np.arange(9).reshape(3,3),columns=   <<< ['A','B','C'],index=['a','b','c'])
<<< df2=pd.DataFrame(np.arange(9).reshape(3,3),columns=   <<< ['D','E','F'],index=['a','b','d'])
# 設置ignore_index=True時,參數keys不起作用
<<< pd.concat([df1,df2],axis=1,ignore_index=True,keys=    <<< ['df1','df2'])
    0	1	2	3	4	5
a	0	1	2	0	1	2
b	3	4	5	3	4	5
c	6	7	8	NaN	NaN	NaN
d	NaN	NaN	NaN	6	7	8
# 設置ignore_index=False,會根據keys的列表標識結果中的數據來源
<<< pd.concat([df1,df2],axis=1,ignore_index=False,keys=   <<< ['df1','df2'])
    df1	        df2
    A	B	C	D	E	F
a	0	1	2	0	1	2
b	3	4	5	3	4	5
c	6	7	8	NaN	NaN	NaN
d	NaN	NaN	NaN	6	7	8

總結:

  • append方法只能進行橫向拼接,且只支持對兩個對象進行拼接操作,但append支持單個對象的連接,此方法常用於循環中;

  • concat方法可用於橫向或縱向的拼接,同時可以設置以並集或交集的方式拼接

如對append和concat方法還感興趣,建議可前往查看官方文檔:

1)https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html?highlight=append#pandas.DataFrame.append

2)pandas.concat - pandas 0.21.0 documentation

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章