如何解决Pandas中的wide_to_long错误 [英] How to resolve wide_to_long error in pandas

查看:59
本文介绍了如何解决Pandas中的wide_to_long错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have following dataframe And I want to convert it into the following format:-

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

To do so I have used the following code snippet:-

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

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

But we are getting below errors::

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

推荐答案

您可以使用numpy concatenate 像这样:

You can use numpy concatenate like that:

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):


Update for variable number of column names (e.g. 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]))

这篇关于如何解决Pandas中的wide_to_long错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆