How to transform/map multi-label index pandas Series to Dataframe?

Question:

I have a pandas Series with multiple index label columns.

I’d like to be able to transform or map that Series into a Dataframe:

Series with multi-index (capability_name and collection_title):

capability_name  collection_title
Capability_01       Jan 2023            3.714286
                    Jul 2022            3.545455
Capability_02       Jan 2023            4.000000
                    Jul 2022            3.760000
Capability_03       Jan 2023            3.666667
                    Jul 2022            3.529412
Capability_04       Jan 2023            3.000000
                    Jul 2022            3.000000
Capability_05       Jan 2023            2.600000
                    Jul 2022            2.750000

Name: capability_score, dtype: float64>

Would like to transform/map to a dataframe
e.g., dataframe_capability_score:
Would like to map to a dataframe:

                    Jul 2022          Jan 2023
Capability_01       3.545455          3.714286
Capability_02       3.760000          4.000000
Capability_03       3.529412          3.666667
Capability_04       3.000000          3.000000
Capability_05       2.750000          2.600000

I haven’t been able to make it happen. I’ve tried a pandas pivot table but feel that’s on the wrong track.

Asked By: PeDey

||

Answers:

Convert the Series to a Dataframe and "flattening" the multiple index cols:

df = capability_score.to_frame() 
df = df.reset_index()

Then use df.pivot():

out = df.pivot(index='capability_name', columns='collection_title', values='capability_score')
out = out[['Jul 2022', 'Jan 2023']]
print(out)

collection_title  Jul 2022  Jan 2023
capability_name                     
Capability_01     3.545455  3.714286
Capability_02     3.760000  4.000000
Capability_03     3.529412  3.666667
Capability_04     3.000000  3.000000
Capability_05     2.750000  2.600000
Answered By: Jamiu S.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.