合并含固定列与不定列的多个pandas DataFrame方法咨询
你可以直接使用pandas的concat方法实现需求,默认纵向拼接时会自动对齐所有列名,不存在的列填充NaN,代码如下:
import pandas as pd # 直接拼接所有DataFrame,忽略原有子表的行索引 resultDf = pd.concat(appendDataFrames, ignore_index=True) # 若需严格保证前5列为固定静态列,其余列按规则排序,可额外调整列顺序 static_columns = ['static_1', 'static_2', 'static_3', 'static_4', 'static_5'] # 下面代码将非固定列按首字母排序,也可根据需求调整排序规则 dynamic_columns = sorted([col for col in resultDf.columns if col not in static_columns]) resultDf = resultDf.reindex(columns=static_columns + dynamic_columns)
上述代码兼容你使用的pandas 0.17.1版本,运行后得到的结果和你给出的预期输出完全一致。
内容的提问来源于stack exchange,提问作者Nicko
相关产品推荐
相关产品推荐

