如何解决Pandas中的wide_to_long错误

时间:2019-12-10 12:38:13

标签: python python-3.x pandas

我有以下数据框 enter image description here 我想将其转换为以下格式: enter image description here

为此,我使用了以下代码段:-

df = pd.wide_to_long(df, stubnames=['manufacturing_unit_','outlet_','inventory','year'],i=['Brand','customer name','Factory'],j='drop').reset_index().drop('drop', 1)

但是我们遇到了以下错误:

1) ValueError: stubname can't be identical to a column name
2) the id variables need to uniquely identify each row

1 个答案:

答案 0 :(得分:0)

您可以像这样使用numpy concatenate

res = pd.DataFrame(pd.np.concatenate([df.iloc[:,[0,1,2,3,6,9,12]], df.iloc[:,[0,1,2,4,7,10,13]], df.iloc[:,[0,1,2,5,8,11,14]]]))
res.columns = ['Brand', 'customer name', 'Factory', 'manufacturing', 'outlet', 'inventory', 'year']


更新以获取可变数量的列名(例如1 ... 3):

cols = [f'Brand|customer name|Factory|{x}$' for x in range(1,4)]
pd.DataFrame(pd.np.concatenate([df.filter(regex=col) for col in cols]))