Skip to content

Instantly share code, notes, and snippets.

@RenSys
Last active October 17, 2021 13:15
Show Gist options
  • Save RenSys/2b97857f3921dca643bacebdbf7397d6 to your computer and use it in GitHub Desktop.
Save RenSys/2b97857f3921dca643bacebdbf7397d6 to your computer and use it in GitHub Desktop.
[Groupby & apply - Single Line] #pandas #groupby #apply
import pandas as pd
df = pd.DataFrame([
[123, 'abc'],
[123, 'abc'],
[456, 'def'],
[123, 'abc'],
[123, 'abc'],
[456, 'def'],
[456, 'def'],
[456, 'def'],
], columns = ['userid', 'name'])
df1 = df.sort_values('userid').groupby('userid')['name'].apply(lambda df: df.reset_index(drop = True)).unstack()
print(df1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment