Skip to content

Instantly share code, notes, and snippets.

@deanjamesss
Created January 29, 2021 01:24
Show Gist options
  • Select an option

  • Save deanjamesss/9ee53f6789f6fab2966a054f09c9fc82 to your computer and use it in GitHub Desktop.

Select an option

Save deanjamesss/9ee53f6789f6fab2966a054f09c9fc82 to your computer and use it in GitHub Desktop.
import pandas as pd
if __name__ == '__main__':
# Create a DataFrame with dummy data.
df = pd.DataFrame(data={'staff_no': [9999] * 5,
'name': ['Dean McGrath'] * 5,
'year': [2016, 2017, 2018, 2019, 2020],
'hours': [349, 231, 876, 679, 976]})
# Pivot the DataFrame based on Staff Number & Employee Name.
df = df.pivot(index=['staff_no', 'name'],
columns=['year'], values='hours').reset_index()
print(df.head())
# Unpivot the DataFrame by Staff Number & Employee Name
df = df.melt(id_vars=['staff_no', 'name'], var_name='year',
value_name='hours')
print(df.head())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment