Pandas partial melt or group melt

2024/9/20 18:32:30

I have a DataFrame like this

>>> df = pd.DataFrame([[1,1,2,3,4,5,6],[2,7,8,9,10,11,12]], columns=['id', 'ax','ay','az','bx','by','bz'])
>>> dfid  ax  ay  az  bx  by  bz
0   1   1   2   3   4   5   6
1   2   7   8   9  10  11  12

and I want to transform it into something like this

   id name   x   y   z
0   1    a   1   2   3
1   2    a   7   8   9
2   1    b   4   5   6
3   2    b  10  11  12

This is an unpivot / melt problem, but I don't know of any way to melt by keeping these groups intact. I know I can create projections across the original dataframe and then concat those but I'm wondering if I'm missing some common melt tricks from my toolbelt.

Answer

Set_index, convert columns to multi index and stack,

df = df.set_index('id')
df.columns = [df.columns.str[1], df.columns.str[0]]
new_df = df.stack().reset_index().rename(columns = {'level_1': 'name'})id  name    x   y   z
0   1   a       1   2   3
1   1   b       4   5   6
2   2   a       7   8   9
3   2   b       10  11  12
https://en.xdnf.cn/q/72469.html

Related Q&A

How do I detect when my window is minimized with wxPython?

I am writing a small wxPython utility.I would like to use some event to detect when a user minimizes the application/window.I have looked around but did not find an event like wx.EVT_MINIMIZE that I co…

Pandas: How to select a column in rolling window

I have a dataframe (with columns a, b, c) on which I am doing a rolling-window.I want to be able to filter the rolling window using one of the columns (say a) in the apply function like belowdf.rolling…

What is the fastest way in Cython to create a new array from an existing array and a variable

Suppose I have an arrayfrom array import array myarr = array(l, [1, 2, 3])and a variable: myvar = 4 what is the fastest way to create a new array:newarray = array(l, [1, 2, 3, 4])You can assume all ele…

Subclassing and built-in methods in Python

For convenience, I wanted to subclass socket to create an ICMP socket:class ICMPSocket(socket.socket):def __init__(self):socket.socket.__init__(self, socket.AF_INET,socket.SOCK_RAW,socket.getprotobynam…

How to load Rs .rdata files into Python?

I am trying to convert one part of R code in to Python. In this process I am facing some problems.I have a R code as shown below. Here I am saving my R output in .rdata format.nms <- names(mtcars) s…

how to set cookie in python mechanize

After sending request to the serverbr.open(http://xxxx)br.select_form(nr=0) br.form[MESSAGE] = 1 2 3 4 5br.submit()I get the response title, which has set-cookieSet-Cookie: PON=xxx.xxx.xxx.111; expir…

How can I deal with a massive delete from Django Admin?

Im working with Django 2.2.10.I have a model called Site, and a model called Record. Each record is associated with a single site (Foreign Key).After my app runs for a few days/weeks/months, each site …

What is colocate_with used for in tensorflow?

Here is the link of the official docs. https://www.tensorflow.org/versions/r1.3/api_docs/python/tf/colocate_with

Getting tkinter to work with python 3.x on macos with asdf [duplicate]

This question already has answers here:Why does tkinter (or turtle) seem to be missing or broken? Shouldnt it be part of the standard library?(4 answers)Closed 8 months ago.So Im stumped. How do I ge…

Flask server sent events socket exception

I am thinking of using SSE to push new data to the client and using Flot(javascript charting library) display "live" updates. My server runs on python Flask framework and I have figured out h…