Skip to content Skip to sidebar Skip to footer

Python Pandas: Transpose Or Stack?

Hello I have an example data frame below. I am having trouble obtain the desired results through transpose.... x = ('P', 'P', 'O', 'DNP', 'D') y = ('O', 'O', 'D', 'DNP', 'DNP') z

Solution 1:

You could use pd.melt:

In[23]: pd.melt(df, id_vars=['id'], var_name='colvals', value_name='DOPU')
Out[23]: 
     idcolvalsDOPU0ID1aO1ID2aO2ID3aD
...
21ID2zP22ID3zO23ID4zU24ID5zDNP

Or, alternatively, you could set id as the index before calling stack:

In[21]: df.set_index('id').stack()
Out[21]: 
idID1aObPxPyOzP
...         
ID5aDNPbDNPxDyDNPzDNPdtype: object

stack moves the column level values into the index. Since the desired result has id values in the index as well, it is natural to use set_index to move the id column into the index first, and then to call stack.


Call reset_index to move the index levels into DataFrame columns:

In [164]: df.columns.name = 'colvals'
In [165]: df.set_index('id').stack().reset_index()
Out[165]: 
     id colvals    00   ID1       a    O
1   ID1       b    P
2   ID1       x    P
3   ID1       y    O
4   ID1       z    P
...
20  ID5       a  DNP
21  ID5       b  DNP
22  ID5       x    D
23  ID5       y  DNP
24  ID5       z  DNP

Post a Comment for "Python Pandas: Transpose Or Stack?"