追加 Pandas 个数据帧 - 索引不匹配

Appending Pandas DataFrames - indexing not matching

pandas 的新手和一个简单的追加让我感到难过。我基本上已经旋转数据来创建一个像这样的原始数据框:

df_dict['Parish_Totals'] = pd.pivot_table(df_dict['S106'], values=['AP','AS'], index=['PARISH'],columns=['Covenant Area'], aggfunc=np.sum, fill_value=0)

这工作正常,但显然 return 任何不在数据集中的教区都不会开始。客户需要一个完整的教区列表(没有价值的地方为零)。为此,我得到了所有教区的列表,然后将该列表与我有数据的教区进行比较,以获取那些不在需要添加到其中的数据中的教区。我这样做很好:

# List of zeros to populate fields for additional parishes with no data missing from pivot
zeros = [0]*10
list_of_rows_to_add = []
# List of columns to match the pivoted data
column_heads = ['PARISH', 'POS_AP',  'POS_AS', 'ED_AP', 'ED_AS', 'TH_AP', 'TH_AS', 'AH_AP', 'AH_AS', 'OT_AP', 'OT_AS']

# For every parish not featured in the pivot (with no data to display)

for parish in all_parishes:

    if parish not in df_dict['Parish_Totals'].index:
        
        # Create a list of values for a new row, starting with the parish name at position 0

        row_to_add = zeros.copy()

        row_to_add.insert(0,parish)

        # Add the new row to the list of rows to be added
        list_of_rows_to_add.append(row_to_add)
        
df_dict['Empty_Parishes'] = pd.DataFrame(list_of_rows_to_add, columns = column_heads)
        
df_dict['Empty_Parishes'].set_index('PARISH')

这看起来也不错,所以我认为我需要做的就是将旋转数据附加到我的零值数据。

df_dict['NEW'] = df_dict['Parish_Totals'].append(df_dict['Empty_Parishes'])

然而,当我这样做时,它似乎忽略了 'PARISH' 索引:

如果我在我的旋转数据上调用索引,我得到这个:

索引(['Altarnun', 'Bodmin', 'Breage', 'Bude-Stratton', 'Budock', 'Callington', 'Calstock', 'Camborne', 'Camelford', 'Cardinham', ... 'Tregony with Cuby', 'Treverbyn', 'Truro', 'Tywardreath and Par', 'Veryan', 'Wadebridge', 'Week St. Mary', 'Wendron', 'Whitstone', 'Withiel'], dtype='object', 名称='PARISH', 长度=150)

而如果我在我附加的 'zero' 数据上调用索引,我会得到:

RangeIndex(开始=0,停止=62,步长=1)

同样,如果我在零数据集上调用 'columns',它包括 'PARISH',而在我的旋转 df 上,'PARISH' 未列出(大概是因为它是一个索引)。

我花了很多时间试图弄清楚我所期望的是一件非常简单的事情。谁能把我从痛苦中解救出来?谢谢:)

可能更容易做到 merge

#create a pandas series from all_parishes
df_all_parishes =  pd.DataFrame(all_parishes, columns=['parish'])

result = df_all_parishes.merge(right=df_pivot_table, how='left').fillna(value=0) 

您需要根据要合并的内容更改参数。因为它将合并具有相同名称的列,即 'parish' 应该是一个公共列。不确定你是否将它作为你的索引 table,如果是这样你可以 reset_index() 更改为数字范围索引