首页 > 解决方案 > 如何解决熊猫中的wide_to_long错误

问题描述

我有以下数据框 在此处输入图像描述 ,我想将其转换为以下格式:- 在此处输入图像描述

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

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

标签: pythonpython-3.xpandas

解决方案


你可以像这样使用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]))

推荐阅读