简体   繁体   中英

Why can't I unpivot (melt) this panda dataframe (python)

I have a panda data frame that I made and I pivoted it the exact way I want it. Now, I want to unpivot everything to get the position data (row and column) with the newly formed data frame and see which. For example, I want for the first row (in the new data frame that is unpivoted with the position data) to have 1 under "row", 1 under "a", and 1 as the value (example below). Can someone please figure out how I can unpivot to get the row and column values? I have tried used pd.melt but it didn't seem to work (it made no difference). Please respond soon. Thanks. Directly below is code to make the pivoted data frame.

import pandas as pd
row = [1, 2, 3, 4, 5]
df67 = {'row':row,}
df67 = pd.DataFrame(df67,columns=['row'])
df67['a'] = [1, 2, 3, 4, 5]
df67['b'] =[13, 18, 5, 10, 6]
#df67 (dataframe before pivot)
df68 = df67.pivot(index='row', columns = 'a')
#df68 (dataframe after pivot)

What I want the result to be for the first line: row | a | value 1 | 1 | 13

Use DataFrame.stack with DataFrame.reset_index :

df = df68.stack().reset_index()
print (df)
   row  a     b
0    1  1  13.0
1    2  2  18.0
2    3  3   5.0
3    4  4  10.0
4    5  5   6.0

EDIT:

For avoid removed missing values use dropna=False parameter:

df = df68.stack(dropna=False).reset_index()
print (df)
    row  a     b
0     1  1  13.0
1     1  2   NaN
2     1  3   NaN
3     1  4   NaN
4     1  5   NaN
5     2  1   NaN
6     2  2  18.0
7     2  3   NaN
8     2  4   NaN
9     2  5   NaN
10    3  1   NaN
11    3  2   NaN
12    3  3   5.0
13    3  4   NaN
14    3  5   NaN
15    4  1   NaN
16    4  2   NaN
17    4  3   NaN
18    4  4  10.0
19    4  5   NaN
20    5  1   NaN
21    5  2   NaN
22    5  3   NaN
23    5  4   NaN
24    5  5   6.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM