Skip to content

Instantly share code, notes, and snippets.

@owlas
Created November 23, 2016 17:49
Show Gist options
  • Save owlas/ee0acaa8077b64cf7fe172db5555bd52 to your computer and use it in GitHub Desktop.
Save owlas/ee0acaa8077b64cf7fe172db5555bd52 to your computer and use it in GitHub Desktop.
Reshape pandas data frame by grouping rows and casting into new columns
import pandas as pd
# an example dataframe
df = pd.DataFrame.from_dict({
'content': ['some content', 'and text', 'more writing', 'words in a line'],
'url': ['a-url.com', 'cool.ai', 'random.xyz', 'here.there']
})
Nbins = 3
# use pivoting to create new rows
df['col'] = df.index.map(lambda x: x%Nbins)
df['idx'] = df.index.map(lambda x: x//Nbins)
pivoted = df.pivot(index='idx', columns='col')
pivoted.columns = ['{}_{}'.format(l[0], l[1]) for l in pivoted.columns.tolist()]
# finished
print(pivoted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment