如何合并堆叠列结构不同的两个Pandas DataFrame
你这个需求本质是两个结构相似的DataFrame按行纵向堆叠,Pandas内置的pd.concat()方法可以直接满足要求,它会自动按列名对齐,某一方不存在的列会自动填充缺失值,不需要额外写复杂的合并逻辑。
实现代码
import pandas as pd # 构造df1(原有代码) d1 = {'Location+Type':['Census Tract 3, Jefferson County, Alabama: Summary level: 140, state:01> county:073> tract:000300', 'Census Tract 4, Jefferson County, Alabama: Summary level: 140, state:01> county:073> tract:000400','Census Tract 5, Jefferson County, Alabama: Summary level: 140, state:01> county:073> tract:000500'], 'Year':['2009','2009','2009'], 'state':['Alabama','Alabama','Alabama'], 'Census_tract':[3,3,3], 'County_name':['Jefferson County','Jefferson County','Jefferson County'], 'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9], } df1 = pd.DataFrame(data=d1) # 构造df2(原有代码) d2 = {'Location+Type':['Census Tract 3, Jefferson County, Alabama: Summary level: 140, state:01> county:073> tract:000300', 'Census Tract 4, Jefferson County, Alabama: Summary level: 140, state:01> county:073> tract:000400','Census Tract 5, Jefferson County, Alabama: Summary level: 140, state:01> county:073> tract:000500'], 'Year':['2010','2010','2010'], 'state':['Alabama','Alabama','Alabama'], 'Census_tract':[3,3,3], 'County_name':['Jefferson County','Jefferson County','Jefferson County'], 'A':[11,22,33], 'B':[44,55,66], 'C':[77,88,99], 'D': [10,20,30] } df2 = pd.DataFrame(data=d2) # 核心合并代码 df_final = pd.concat([df1, df2], ignore_index=True) # 可选操作:如果需要把默认的NaN转为你示例中的None,添加下面这行即可 df_final['D'] = df_final['D'].where(df_final['D'].notna(), None)
参数说明
ignore_index=True是为了重置合并后的行索引,避免保留两个原始DataFrame的旧索引出现重复的0、1、2,完全匹配你给出的目标数据框的结构要求。
内容的提问来源于stack exchange,提问作者justanewb
相关产品推荐
相关产品推荐

