
本篇文章主要介紹了pandas中對series和dataframe對象進行連接的方法:pd.append()和pd.concat(),文中通過示例代碼對這兩種方法進行了詳細的介紹,希望能對各位python小白的學習有所幫助。
描述:append方法用以在表尾中添加新的行,并返回追加后的數(shù)據(jù)對象,若追加的行中存在原數(shù)據(jù)沒有的列,會新增一列,并用nan填充;若追加的行數(shù)據(jù)中缺少原數(shù)據(jù)某列,同樣以nan填充
語法:df.append(other, ignore_index=False, verify_integrity=False, sort=None)
參數(shù)說明:
下面對append方法的每個參數(shù)進行詳細介紹:
第一個參數(shù)為other:要追加的數(shù)據(jù),可以是dataframe,series,字典,列表甚至是元素;但前后類型要一致。
# 將數(shù)據(jù)追加到series <<< a=df.iloc[0,:] <<< b=df.iloc[6,:] <<< a.append(b) #需賦給新值,不改變原數(shù)組 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
# 將數(shù)據(jù)追加到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
注意:獲取單行得到的結果是一維數(shù)組,當一維數(shù)組[6,:]和二維數(shù)組[2,6]追加時,會得到8*7的數(shù)組,匹配不上的地方用NA填充。
# 將二維數(shù)組追加到一維數(shù)組 <<< 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
# 列表追加到列表 <<< 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]
<<< df1=pd.DataFrame() <<< a={'A':1,'B':2} <<< df1=df1.append(a,ignore_index=True) <<< df1 A B 0 1 2
append方法也可以將單個元素追加到列表(其他對象不行),會自動將單個元素轉為列表對象,再進行追加操作
# 單個元素進行追加 <<< a=[1,2,3,4,5,6,7,8] <<< a.append(9) <<< a [1, 2, 3, 4, 5, 6, 7, 8, 9]
<<< df1=pd.DataFrame() <<< ser=pd.Series({"x":1,"y":2},name="a") <<< df1=df1.append(ser) <<< df1 x y a 1 2
如果不添加name,也可以添加參數(shù)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
第二個參數(shù):兩個表的index是否有實際含義,默認ignore_index=False,若為True,表根據(jù)列名對齊合并,生成新的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
第三個參數(shù)為verify_integrity:默認為False 參數(shù)用于檢查結果對象新連接軸上的索引是否有重復項,有的話引發(fā) ValueError,可以看到這個參數(shù)的作用與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則會報錯。
第四個參數(shù)為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
描述:concat方法用以將兩個或多個pandas對象根據(jù)軸(橫向/縱向)進行拼接,concat函數(shù)是在pandas命名空間下的方法,因此需要通過pd.concat()的方式來引用。
語法:pd.concat(‘objs’, ‘a(chǎn)xis=0’, “join=‘outer’”, ‘join_axes=None’, ‘ignore_index=False’, ‘keys=None’, ‘levels=None’, ‘names=None’, ‘verify_integrity=False’, ‘sort=None’, ‘copy=True’)
常用參數(shù):
下面,將對concat方法以上各個參數(shù)進行詳細說明:
第一個要學習的參數(shù)為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
<<< 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
第二個要學習的參數(shù)為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']) # 將數(shù)據(jù)對象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
第三個要學習的參數(shù)為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
第四個要學習的參數(shù)為join_axes:以哪個數(shù)據(jù)對象的index/columns作為軸進行拼接,當進行橫向拼接時,join_axes為index的列表,如需根據(jù)df1對齊數(shù)據(jù),則會保留df1的index,再將df2的數(shù)據(jù)進行拼接;同理,縱向拼接時為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']) # 根據(jù)df1的index對齊數(shù)據(jù) <<< 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 # 根據(jù)df2的index對齊數(shù)據(jù) <<< 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
第五個要學習的參數(shù)為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
第六個要學習的參數(shù)為keys:表標識的列表,用來區(qū)分合并后的數(shù)據(jù)來源于哪個表,當ignore_index=True時,此參數(shù)的作用失效。
<<< 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時,參數(shù)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,會根據(jù)keys的列表標識結果中的數(shù)據(jù)來源 <<< 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和concat方法還感興趣,建議可前往查看官方文檔:
1)https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html?highlight=append#pandas.DataFrame.append
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
SQL Server 中 CONVERT 函數(shù)的日期轉換:從基礎用法到實戰(zhàn)優(yōu)化 在 SQL Server 的數(shù)據(jù)處理中,日期格式轉換是高頻需求 —— 無論 ...
2025-09-18MySQL 大表拆分與關聯(lián)查詢效率:打破 “拆分必慢” 的認知誤區(qū) 在 MySQL 數(shù)據(jù)庫管理中,“大表” 始終是性能優(yōu)化繞不開的話題。 ...
2025-09-18CDA 數(shù)據(jù)分析師:表結構數(shù)據(jù) “獲取 - 加工 - 使用” 全流程的賦能者 表結構數(shù)據(jù)(如數(shù)據(jù)庫表、Excel 表、CSV 文件)是企業(yè)數(shù)字 ...
2025-09-18DSGE 模型中的 Et:理性預期算子的內(nèi)涵、作用與應用解析 動態(tài)隨機一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開始提取前,需先判斷 TIF 文件的類型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結構數(shù)據(jù)特征價值的專業(yè)核心 表結構數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲的結構化數(shù)據(jù),如數(shù)據(jù)庫表、Excel 表、 ...
2025-09-17Excel 導入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實戰(zhàn)應用 在用 Python(如 pandas 庫)處理 Excel 數(shù)據(jù)時,“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗與 t 檢驗:差異、適用場景與實踐應用 在數(shù)據(jù)分析與統(tǒng)計學領域,假設檢驗是驗證研究假設、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結構數(shù)據(jù)全功能周期的專業(yè)操盤手 表格結構數(shù)據(jù)(以 “行 - 列” 存儲的結構化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計劃中 rows 數(shù)量的準確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對象的 text 與 content:區(qū)別、場景與實踐指南 在 Python 進行 HTTP 網(wǎng)絡請求開發(fā)時(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結構數(shù)據(jù)價值的核心操盤手 表格結構數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫表)是企業(yè)最基礎、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請求工具對比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長浮點數(shù)據(jù)的科學計數(shù)法問題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長浮點數(shù)據(jù)時的科學計數(shù)法問題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務數(shù)據(jù)分析步驟的落地者與價值優(yōu)化者 業(yè)務數(shù)據(jù)分析是企業(yè)解決日常運營問題、提升執(zhí)行效率的核心手段,其價值 ...
2025-09-12用 SQL 驗證業(yè)務邏輯:從規(guī)則拆解到數(shù)據(jù)把關的實戰(zhàn)指南 在業(yè)務系統(tǒng)落地過程中,“業(yè)務邏輯” 是連接 “需求設計” 與 “用戶體驗 ...
2025-09-11塔吉特百貨孕婦營銷案例:數(shù)據(jù)驅動下的精準零售革命與啟示 在零售行業(yè) “流量紅利見頂” 的當下,精準營銷成為企業(yè)突圍的核心方 ...
2025-09-11CDA 數(shù)據(jù)分析師與戰(zhàn)略 / 業(yè)務數(shù)據(jù)分析:概念辨析與協(xié)同價值 在數(shù)據(jù)驅動決策的體系中,“戰(zhàn)略數(shù)據(jù)分析”“業(yè)務數(shù)據(jù)分析” 是企業(yè) ...
2025-09-11Excel 數(shù)據(jù)聚類分析:從操作實踐到業(yè)務價值挖掘 在數(shù)據(jù)分析場景中,聚類分析作為 “無監(jiān)督分組” 的核心工具,能從雜亂數(shù)據(jù)中挖 ...
2025-09-10統(tǒng)計模型的核心目的:從數(shù)據(jù)解讀到?jīng)Q策支撐的價值導向 統(tǒng)計模型作為數(shù)據(jù)分析的核心工具,并非簡單的 “公式堆砌”,而是圍繞特定 ...
2025-09-10