【发布时间】:2021-10-10 08:00:07
【问题描述】:
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)
这很好用,但显然不会返回任何不在数据集中的教区。客户需要完整的教区列表(没有价值的地方用零)。为此,我得到了所有教区的列表,然后将该列表与我拥有数据的教区进行比较,以获取那些不在需要添加到其中的数据中的教区。我这样做没问题:
# 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'])
但是,当我这样做时,它似乎忽略了“教区”索引:
如果我在我的透视数据上调用索引,我会得到:
Index(['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'、 '与尼尔'], dtype='object', name='PARISH', 长度=150)
而如果我在我要附加的“零”数据上调用索引,我会得到这个:
RangeIndex(start=0, stop=62, step=1)
类似地,如果我在零数据集上调用“列”,它包括“教区”,而在我的旋转 df 上,“教区”未列出(可能是因为它是一个索引)。
我花了很多时间试图弄清楚我所期望的是一件非常简单的事情。谁能把我从痛苦中解救出来?谢谢:)
【问题讨论】:
标签: python pandas dataframe indexing append