How to resolve wide_to_long error in pandas

2024/11/16 4:45:48

I have following dataframe enter image description here And I want to convert it into the following format:- enter image description here

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
Answer

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']


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]))
https://en.xdnf.cn/q/119574.html

Related Q&A

Odoo 10: enter value in Many2one field dynamically

I added in my models.py :commercial_group = fields.Many2one("simcard.simcard")and in my views.xml :<field name="commercial_group" widget="selection"/>And then i am t…

How to erode this thresholded image using OpenCV

I am trying to first remove the captcha numbers by thresholding and then eroding it ,to get slim continuous lines to get better output. Problem:the eroded image is not continuous as u can see Original …

Searching for only the first value in an array in a csv file

So i am creating a account login system which searches a database for a username (and its relevant password) and, if found, will log the user on.This is what the csv file currently looks like[dom, ente…

how to write a single row cell by cell and fill it in csv file

I have a CSV file that only has column headers:cat mycsv.csvcol_1@@@col_2@@@col_3@@@col_3I have to fill a single row with None values in each cell of the CSV file. Can someone suggest me the best-optim…

Greedy String Tiling in Python

I am trying to learn greedy string tiling in algorithmI have two lists as follows:a=[a,b,c,d,e,f] b=[d,e,a,b,c,f]i would like to retrieve c=[a,b,c,d,e]Another example would be a = [1,2,3,4,5,6,7,8,9,1,…

Python - efficient way to create 20 variables?

I need to create 20 variables in Python. That variables are all needed, they should initially be empty strings and the empty strings will later be replaced with other strings. I cann not create the var…

Whatsapp asking for updating chrome version

I am trying to open whatsapp with selenium and python, it was working fine until today. In headless or non, whatsapp is now asking to update chrome, when I try to do so, Chrome throws this error: An er…

how to find the longest N words from a list, using python?

I am now studying Python, and I am trying to solve the following exercise:Assuming there is a list of words in a text file, My goal is to print the longest N words in this list.Where there are several …

([False, True] and [True, True]) evaluates to [True, True]

I have observed the following behavior in python 3: >>> ([False, True] and [True, True]) [True, True]>>> ([False, True] or [True, True]) [False, True]I was expecting exactly the oppos…

Uploading an image to Flask server

I am struggling bit with Flask and uploading a file, here is my Flask code so far:@app.route(/api/user/update/, methods=[PUT]) @auth.login_required def update_user():# check if the post request has the…