1

Here is the data frame I have

          Temp  Time
Date                
20220110    65     1
20220111    55     1
20220112    32     1
20220110    66     2
20220111    54     2
20220112    30     2
20220110    68     3
20220111    50     3
20220112    28     3

What I am looking for is

Time         1     2     3
Date                
20220110    65     66    32
20220111    55     54    50
20220112    32     30    28

I think it is a groupby command or something simple, I just can't figure it out. Here is the code to create the data frame:

import pandas as pd

# initialize data of lists.
data = {'Date': ['20220110', '20220111', '20220112', '20220110', '20220111', '20220112', '20220110', '20220111', '20220112',],
        'Temp': [65, 55, 32, 66, 54, 30, 68, 50, 28],
        'Time': [1, 1, 1, 2, 2, 2, 3, 3, 3]}

# Create DataFrame
df = pd.DataFrame(data).set_index('Date')

# Print the output.
print(df)
Rob Lasch
  • 95
  • 5

2 Answers2

2

You can also use pivot:

out = df.reset_index().pivot('Date','Time','Temp')

Output:

Time       1   2   3
Date                
20220110  65  66  68
20220111  55  54  50
20220112  32  30  28
0

Try, move Time into the index with set_index and parameter append and then unstack the inner most level of the index:

 df.set_index('Time', append=True)['Temp'].unstack()

Output:

Time       1   2   3
Date                
20220110  65  66  68
20220111  55  54  50
20220112  32  30  28
Scott Boston
  • 147,308
  • 15
  • 139
  • 187