为了账号安全,请及时绑定邮箱和手机立即绑定

根据 pivot_table 的输出动态重命名数据框

根据 pivot_table 的输出动态重命名数据框

守着星空守着你 2023-06-06 17:38:28
我试图以一种格式压缩我的数据,这样它会更有用,数据格式:Table1Key       AttName     Rank1          Color       11           type       21           kkk        32          Color       12           type       2     如上图所示,例如,一些键有 2 个属性,而其他键有 3 个属性,所以当我创建数据透视表然后尝试标记它不起作用的列名时,hpw 我可以更改它吗,正如上面显示的那样,键 1 有 3 个属性名称而 Key 2 只有 2 个导致错误发生最终数据:Table2Family     Assortment Group       Key       Attribute Name      Attribute Valuea                ab                1            Color              Greena1               ab                1            Color              Yellowa2               ab                1            type               shirta6               ab                1            kkkk               fa3               ab                2            Color              Reda4               ab                2            Type               TShirta5               ab                2            Color              Yellow代码#For loop that loops over key values; key values defined as Zone AGFinals=[]Finals2=[]Finals=pd.DataFrame(Finals)Finals2=pd.DataFrame(Finals)for group in Select.groupby('Key'):     # group is a tuple where the first value is the Key and the second is the dataframe    Final2=group[1]    Family1=Family.merge(Final2, on='Key1', how='inner')    result=Family1.pivot_table(index=['Family','Assortment Group','Key'], columns='Attribute Name', values='Attribute Value', aggfunc='first').reset_index()    result.columns=['Family','Assortment Group','Key','Att1','Att2','Att3']    Finals=Finals.append(result)追溯ValueError: Length mismatch: Expected axis has 5 elements, new values have 6 elements
查看完整描述

1 回答

?
慕妹3242003

TA贡献1824条经验 获得超6个赞

您可以使用列表理解重命名列以生成适量的 Att 列。

result.columns = ['Family','Assortment Group','Key']\
                 + [f'Att{i}' for i in range(1, result.shape[1]-2)]

编辑:解释,result.shape[1]给出结果中的列数。假设它是 5,那么前 3 个是“Family”、“Assortment Group”、“Key”。所以你想要的是再创建 2 个 Att,range(1, result.shape[1]-2)在这种情况下range(1, 3)[f'Att{i}' for i in range(1, result.shape[1]-2)]然后将迭代 i=1 和 i=2 以创建列表['Att1', 'Att2']。将此列表添加到具有前 3 列名称的列表中以获得正确的列数


查看完整回答
反对 回复 2023-06-06
  • 1 回答
  • 0 关注
  • 114 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信