Created
November 23, 2016 17:49
-
-
Save owlas/ee0acaa8077b64cf7fe172db5555bd52 to your computer and use it in GitHub Desktop.
Reshape pandas data frame by grouping rows and casting into new columns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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